]> git.mxchange.org Git - jfinancials-war.git/blob
5b63e2c4c706698e273e9802f8aad876c2a28a64
[jfinancials-war.git] /
1 /*
2  * Copyright (C) 2016 - 2022 Free Software Foundation
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License as
6  * published by the Free Software Foundation, either version 3 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU Affero General Public License for more details.
13  *
14  * You should have received a copy of the GNU Affero General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jfinancials.beans.financial.model.receipt_item.list;
18
19 import fish.payara.cdi.jsr107.impl.NamedCache;
20 import java.text.MessageFormat;
21 import java.util.Comparator;
22 import java.util.Iterator;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Objects;
26 import javax.annotation.PostConstruct;
27 import javax.cache.Cache;
28 import javax.ejb.EJB;
29 import javax.enterprise.event.Observes;
30 import javax.faces.view.ViewScoped;
31 import javax.inject.Inject;
32 import javax.inject.Named;
33 import org.mxchange.jfinancials.beans.BaseFinancialsBean;
34 import org.mxchange.jfinancials.beans.user.login.FinancialsUserLoginWebSessionController;
35 import org.mxchange.jfinancials.events.receipt_item.added.ObservableAdminReceiptItemAddedEvent;
36 import org.mxchange.jfinancials.events.receipt_item.updated.ObservableAdminReceiptItemUpdatedEvent;
37 import org.mxchange.jfinancials.exceptions.receipt_item.ReceiptItemNotFoundException;
38 import org.mxchange.jfinancials.model.receipt_item.BillableReceiptItem;
39 import org.mxchange.jfinancials.model.receipt_item.FinancialReceiptItemSessionBeanRemote;
40 import org.mxchange.jfinancials.model.receipt_item.ReceiptItems;
41 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
42
43 /**
44  * A list financial receipt item bean (controller)
45  * <p>
46  * @author Roland Häder<roland@mxchange.org>
47  */
48 @Named ("receiptItemListController")
49 @ViewScoped
50 public class FinancialsReceiptItemListWebViewBean extends BaseFinancialsBean implements FinancialsReceiptItemListWebViewController {
51
52         /**
53          * Serial number
54          */
55         private static final long serialVersionUID = 56_189_028_928_472L;
56
57         /**
58          * All receipt items list
59          */
60         private final List<BillableReceiptItem> allReceiptItems;
61
62         /**
63          * Filtered receipt items list
64          */
65         private List<BillableReceiptItem> filteredReceiptItems;
66
67         /**
68          * EJB for general financial receipt purposes
69          */
70         @EJB (lookup = "java:global/jfinancials-ejb/financialReceiptItem!org.mxchange.jfinancials.model.receipt_item.FinancialReceiptItemSessionBeanRemote")
71         private FinancialReceiptItemSessionBeanRemote receiptItemBean;
72
73         /**
74          * A list of all branch offices (globally)
75          */
76         @Inject
77         @NamedCache (cacheName = "receiptItemCache")
78         private transient Cache<Long, BillableReceiptItem> receiptItemCache;
79
80         /**
81          * Selected receipt item
82          */
83         private BillableReceiptItem selectedReceiptItem;
84
85         /**
86          * User instance
87          */
88         @Inject
89         private FinancialsUserLoginWebSessionController userLoginController;
90
91         /**
92          * User's receipt items
93          */
94         private final List<BillableReceiptItem> userReceiptItems;
95
96         /**
97          * Constructor
98          */
99         @SuppressWarnings ("CollectionWithoutInitialCapacity")
100         public FinancialsReceiptItemListWebViewBean () {
101                 // Call super constructor
102                 super();
103
104                 // Init lists
105                 this.allReceiptItems = new LinkedList<>();
106                 this.userReceiptItems = new LinkedList<>();
107         }
108
109         /**
110          * Observes events being fired when an administrator has added a new receipt
111          * item.
112          * <p>
113          * @param event Event being fired
114          */
115         public void afterAdminAddedReceiptItemEvent (@Observes final ObservableAdminReceiptItemAddedEvent event) {
116                 // Validate parameter
117                 if (null == event) {
118                         // Throw NPE
119                         throw new NullPointerException("event is null"); //NOI18N
120                 } else if (event.getAddedReceiptItem() == null) {
121                         //Throw NPE again
122                         throw new NullPointerException("event.addedReceiptItem is null"); //NOI18N
123                 } else if (event.getAddedReceiptItem().getItemId() == null) {
124                         //Throw NPE again
125                         throw new NullPointerException("event.addedReceiptItem.itemId is null"); //NOI18N
126                 } else if (event.getAddedReceiptItem().getItemId() < 1) {
127                         //Throw IAE
128                         throw new IllegalArgumentException(MessageFormat.format("event.addedReceiptItem.itemId={0} is not valid", event.getAddedReceiptItem().getItemId())); //NOI18N
129                 }
130
131                 // Uniquely add to cache
132                 this.uniqueAddReceiptItem(event.getAddedReceiptItem());
133         }
134
135         /**
136          * Observes events being fired when an administrator has updated a receipt
137          * item instance.
138          * <p>
139          * @param event Event being fired
140          */
141         public void afterAdminUpdatedReceiptItemEvent (final @Observes ObservableAdminReceiptItemUpdatedEvent event) {
142                 // Validate parameter
143                 if (null == event) {
144                         // Throw NPE
145                         throw new NullPointerException("event is null"); //NOI18N
146                 } else if (event.getUpdatedReceiptItem() == null) {
147                         //Throw NPE again
148                         throw new NullPointerException("event.updatedReceiptItem is null"); //NOI18N
149                 } else if (event.getUpdatedReceiptItem().getItemId() == null) {
150                         //Throw NPE again
151                         throw new NullPointerException("event.updatedReceiptItem.itemId is null"); //NOI18N
152                 } else if (event.getUpdatedReceiptItem().getItemId() < 1) {
153                         //Throw IAE
154                         throw new IllegalArgumentException(MessageFormat.format("event.updatedReceiptItem.itemId={0} is not valid", event.getUpdatedReceiptItem().getItemId())); //NOI18N
155                 }
156
157                 // Uniquely update instance
158                 this.uniqueAddReceiptItem(event.getUpdatedReceiptItem());
159         }
160
161         /**
162          * Event observer for logged-in user
163          * <p>
164          * @param event Event instance
165          */
166         public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
167                 // Event and contained entity instance should not be null
168                 if (null == event) {
169                         // Throw NPE
170                         throw new NullPointerException("event is null"); //NOI18N
171                 } else if (event.getLoggedInUser() == null) {
172                         // Throw NPE again
173                         throw new NullPointerException("event.loggedInUser is null"); //NOI18N
174                 } else if (event.getLoggedInUser().getUserId() == null) {
175                         // userId is null
176                         throw new NullPointerException("event.loggedInUser.userId is null"); //NOI18N
177                 } else if (event.getLoggedInUser().getUserId() < 1) {
178                         // Not avalid id
179                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
180                 }
181
182                 // Fill cache with all found user's receipts
183                 for (final BillableReceiptItem receiptItem : this.allReceiptItems) {
184                         // Is same user?
185                         if (Objects.equals(receiptItem.getItemReceipt().getReceiptUser(), event.getLoggedInUser())) {
186                                 // Yes, then add it
187                                 this.userReceiptItems.add(receiptItem);
188                         }
189                 }
190         }
191
192         @Override
193         public BillableReceiptItem findReceiptItemById (final Long receiptItemId) throws ReceiptItemNotFoundException {
194                 // Validate parameter
195                 if (null == receiptItemId) {
196                         // Throw NPE
197                         throw new NullPointerException("receiptItemId is null");
198                 } else if (receiptItemId < 1) {
199                         // Throw IAE
200                         throw new IllegalArgumentException(MessageFormat.format("receiptItemId={0} is not valid.", receiptItemId));
201                 }
202
203                 // Init instance
204                 BillableReceiptItem receiptItem = null;
205
206                 // Iterate over whole list
207                 for (final BillableReceiptItem currentReceiptItem : this.getAllReceiptItems()) {
208                         // Is the primary key matching?
209                         if (Objects.equals(currentReceiptItem.getItemId(), receiptItemId)) {
210                                 // Yes, then remember and exit iteration
211                                 receiptItem = currentReceiptItem;
212                                 break;
213                         }
214                 }
215
216                 // Is found?
217                 if (null == receiptItem) {
218                         // Not found
219                         throw new ReceiptItemNotFoundException(receiptItemId);
220                 }
221
222                 // Return it
223                 return receiptItem;
224         }
225
226         @Override
227         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
228         public List<BillableReceiptItem> getAllReceiptItems () {
229                 return this.allReceiptItems;
230         }
231
232         /**
233          * Getter for filtered receipt items
234          * <p>
235          * @return Filtered receipts
236          */
237         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
238         public List<BillableReceiptItem> getFilteredReceiptItems () {
239                 return this.filteredReceiptItems;
240         }
241
242         /**
243          * Setter for filtered receipt items
244          * <p>
245          * @param filteredReceiptItems Filtered receipt items
246          */
247         @SuppressWarnings ("AssignmentToCollectionOrArrayFieldFromParameter")
248         public void setFilteredReceiptItems (final List<BillableReceiptItem> filteredReceiptItems) {
249                 this.filteredReceiptItems = filteredReceiptItems;
250         }
251
252         /**
253          * Getter for selected receipt item
254          * <p>
255          * @return Selected receipt item
256          */
257         public BillableReceiptItem getSelectedReceiptItem () {
258                 return this.selectedReceiptItem;
259         }
260
261         /**
262          * Setter for selected receipt item
263          * <p>
264          * @param selectedReceiptItem Selected receipt item
265          */
266         public void setSelectedReceiptItem (final BillableReceiptItem selectedReceiptItem) {
267                 this.selectedReceiptItem = selectedReceiptItem;
268         }
269
270         @PostConstruct
271         public void initCache () {
272                 // Is cache there?
273                 if (!this.receiptItemCache.iterator().hasNext()) {
274                         // Add all
275                         for (final BillableReceiptItem receiptItem : this.receiptItemBean.fetchAllReceiptItems()) {
276                                 // Add it to cache
277                                 this.receiptItemCache.put(receiptItem.getItemId(), receiptItem);
278                         }
279                 }
280
281                 // Is the list empty, but filled cache?
282                 if (this.getAllReceiptItems().isEmpty() && this.receiptItemCache.iterator().hasNext()) {
283                         // Build up list
284                         for (final Cache.Entry<Long, BillableReceiptItem> currentEntry : this.receiptItemCache) {
285                                 // Add to list
286                                 this.getAllReceiptItems().add(currentEntry.getValue());
287                         }
288
289                         // Sort list
290                         this.getAllReceiptItems().sort(new Comparator<BillableReceiptItem>() {
291                                 @Override
292                                 public int compare (final BillableReceiptItem receiptItem1, final BillableReceiptItem receiptItem2) {
293                                         return receiptItem1.getItemId() > receiptItem2.getItemId() ? 1 : receiptItem1.getItemId() < receiptItem2.getItemId() ? -1 : 0;
294                                 }
295                         }
296                         );
297                 }
298         }
299
300         @Override
301         public boolean isReceiptItemAdded (final BillableReceiptItem receiptItem) {
302                 // Does it contain the same object?
303                 if (this.getAllReceiptItems().contains(receiptItem)) {
304                         // Yes, skip below code
305                         return true;
306                 }
307
308                 // Default is not the same
309                 boolean alreadyAdded = false;
310
311                 // Loop over all
312                 for (final BillableReceiptItem item : this.getAllReceiptItems()) {
313                         // Is the same?
314                         if (ReceiptItems.isSameReceiptItem(item, receiptItem)) {
315                                 // Yes, found it
316                                 alreadyAdded = true;
317                                 break;
318                         }
319                 }
320
321                 // Return flag
322                 return alreadyAdded;
323         }
324
325         /**
326          * Uniquely add a receipt item instance.
327          * <p>
328          * @param receiptItem To be added/updated receipt item instance
329          */
330         private void uniqueAddReceiptItem (final BillableReceiptItem receiptItem) {
331                 // Add to cache and general list
332                 this.receiptItemCache.put(receiptItem.getItemId(), receiptItem);
333
334                 // Get iterator
335                 final Iterator<BillableReceiptItem> allIterator = this.getAllReceiptItems().iterator();
336
337                 // Iterate over all entries
338                 while (allIterator.hasNext()) {
339                         // Get current item
340                         final BillableReceiptItem currentReceiptItem = allIterator.next();
341
342                         // It the id matching?
343                         if (Objects.equals(receiptItem.getItemId(), currentReceiptItem.getItemId())) {
344                                 // Yes, then remove it and stop iterating
345                                 allIterator.remove();
346                                 break;
347                         }
348                 }
349
350                 // Re-add it
351                 this.getAllReceiptItems().add(receiptItem);
352
353                 // Is same user?
354                 if (this.userLoginController.isUserLoggedIn() && Objects.equals(receiptItem.getItemReceipt().getReceiptUser(), this.userLoginController.getLoggedInUser())) {
355                         // Get iterator
356                         final Iterator<BillableReceiptItem> userIterator = this.userReceiptItems.iterator();
357
358                         // Iterate over all entries
359                         while (userIterator.hasNext()) {
360                                 // Get current item
361                                 final BillableReceiptItem currentReceiptItem = userIterator.next();
362
363                                 // It the id matching?
364                                 if (Objects.equals(receiptItem.getItemId(), currentReceiptItem.getItemId())) {
365                                         // Yes, then remove it and stop iterating
366                                         userIterator.remove();
367                                         break;
368                                 }
369                         }
370
371                         // Re-add it
372                         this.userReceiptItems.add(receiptItem);
373                 }
374         }
375 }