]> git.mxchange.org Git - jfinancials-war.git/blob
392f4bed1c0ebd6ebc1c68b1a1a49862af1f125f
[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.utils.ReceiptItemUtils;
41 import org.mxchange.jproduct.events.product.updated.ObservableProductUpdatedEvent;
42 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
43
44 /**
45  * A list financial receipt item bean (controller)
46  * <p>
47  * @author Roland Häder<roland@mxchange.org>
48  */
49 @Named ("receiptItemListController")
50 @ViewScoped
51 public class FinancialsReceiptItemListWebViewBean extends BaseFinancialsBean implements FinancialsReceiptItemListWebViewController {
52
53         /**
54          * Serial number
55          */
56         private static final long serialVersionUID = 56_189_028_928_472L;
57
58         /**
59          * All receipt items list
60          */
61         private final List<BillableReceiptItem> allReceiptItems;
62
63         /**
64          * Filtered receipt items list
65          */
66         private List<BillableReceiptItem> filteredReceiptItems;
67
68         /**
69          * EJB for general financial receipt purposes
70          */
71         @EJB (lookup = "java:global/jfinancials-ejb/financialReceiptItem!org.mxchange.jfinancials.model.receipt_item.FinancialReceiptItemSessionBeanRemote")
72         private FinancialReceiptItemSessionBeanRemote receiptItemBean;
73
74         /**
75          * A list of all branch offices (globally)
76          */
77         @Inject
78         @NamedCache (cacheName = "receiptItemCache")
79         private transient Cache<Long, BillableReceiptItem> receiptItemCache;
80
81         /**
82          * Selected receipt item
83          */
84         private BillableReceiptItem selectedReceiptItem;
85
86         /**
87          * User instance
88          */
89         @Inject
90         private FinancialsUserLoginWebSessionController userLoginController;
91
92         /**
93          * User's receipt items
94          */
95         private final List<BillableReceiptItem> userReceiptItems;
96
97         /**
98          * Constructor
99          */
100         @SuppressWarnings ("CollectionWithoutInitialCapacity")
101         public FinancialsReceiptItemListWebViewBean () {
102                 // Call super constructor
103                 super();
104
105                 // Init lists
106                 this.allReceiptItems = new LinkedList<>();
107                 this.userReceiptItems = new LinkedList<>();
108         }
109
110         /**
111          * Observes events being fired when an administrator has added a new receipt
112          * item.
113          * <p>
114          * @param event Event being fired
115          */
116         public void afterAdminAddedReceiptItemEvent (@Observes final ObservableAdminReceiptItemAddedEvent event) {
117                 // Validate parameter
118                 if (null == event) {
119                         // Throw NPE
120                         throw new NullPointerException("event is null"); //NOI18N
121                 } else if (event.getAddedReceiptItem() == null) {
122                         //Throw NPE again
123                         throw new NullPointerException("event.addedReceiptItem is null"); //NOI18N
124                 } else if (event.getAddedReceiptItem().getItemId() == null) {
125                         //Throw NPE again
126                         throw new NullPointerException("event.addedReceiptItem.itemId is null"); //NOI18N
127                 } else if (event.getAddedReceiptItem().getItemId() < 1) {
128                         //Throw IAE
129                         throw new IllegalArgumentException(MessageFormat.format("event.addedReceiptItem.itemId={0} is not valid", event.getAddedReceiptItem().getItemId())); //NOI18N
130                 }
131
132                 // Uniquely add to cache
133                 this.uniqueAddReceiptItem(event.getAddedReceiptItem());
134         }
135
136         /**
137          * Observes events being fired when an administrator has updated a receipt
138          * item instance.
139          * <p>
140          * @param event Event being fired
141          */
142         public void afterAdminUpdatedReceiptItemEvent (final @Observes ObservableAdminReceiptItemUpdatedEvent event) {
143                 // Validate parameter
144                 if (null == event) {
145                         // Throw NPE
146                         throw new NullPointerException("event is null"); //NOI18N
147                 } else if (event.getUpdatedReceiptItem() == null) {
148                         //Throw NPE again
149                         throw new NullPointerException("event.updatedReceiptItem is null"); //NOI18N
150                 } else if (event.getUpdatedReceiptItem().getItemId() == null) {
151                         //Throw NPE again
152                         throw new NullPointerException("event.updatedReceiptItem.itemId is null"); //NOI18N
153                 } else if (event.getUpdatedReceiptItem().getItemId() < 1) {
154                         //Throw IAE
155                         throw new IllegalArgumentException(MessageFormat.format("event.updatedReceiptItem.itemId={0} is not valid", event.getUpdatedReceiptItem().getItemId())); //NOI18N
156                 }
157
158                 // Uniquely update instance
159                 this.uniqueAddReceiptItem(event.getUpdatedReceiptItem());
160         }
161
162         /**
163          * Event observer for updated product data by administrators
164          * <p>
165          * @param event Updated product data event
166          */
167         public void afterProductUpdatedEvent (@Observes final ObservableProductUpdatedEvent event) {
168                 // Event and contained entity instance should not be null
169                 if (null == event) {
170                         // Throw NPE
171                         throw new NullPointerException("event is null"); //NOI18N
172                 } else if (event.getUpdatedProduct() == null) {
173                         // Throw NPE again
174                         throw new NullPointerException("event.updatedProduct is null"); //NOI18N
175                 } else if (event.getUpdatedProduct().getProductId() == null) {
176                         // userId is null
177                         throw new NullPointerException("event.updatedProduct.productId is null"); //NOI18N
178                 } else if (event.getUpdatedProduct().getProductId() < 1) {
179                         // Not avalid id
180                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getUpdatedProduct(), event.getUpdatedProduct().getProductId())); //NOI18N
181                 }
182
183                 // Get iterator from
184                 final Iterator<Cache.Entry<Long, BillableReceiptItem>> iterator = this.receiptItemCache.iterator();
185
186                 // Loop through it
187                 while (iterator.hasNext()) {
188                         // Get next item
189                         final Cache.Entry<Long, BillableReceiptItem> current = iterator.next();
190
191                         // Get current product
192                         final BillableReceiptItem currentItem = current.getValue();
193
194                         // Is the same product id set?
195                         if (event.getUpdatedProduct().getProductId().equals(currentItem.getItemProduct().getProductId())) {
196                                 // Yes, found it, get key
197                                 final Long itemId = current.getKey();
198
199                                 // Set new instance
200                                 currentItem.setItemProduct(event.getUpdatedProduct());
201
202                                 // Update cache
203                                 this.receiptItemCache.put(itemId, currentItem);
204
205                                 // Stop searching here
206                                 break;
207                         }
208                 }
209         }
210
211         /**
212          * Event observer for logged-in user
213          * <p>
214          * @param event Event instance
215          */
216         public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
217                 // Event and contained entity instance should not be null
218                 if (null == event) {
219                         // Throw NPE
220                         throw new NullPointerException("event is null"); //NOI18N
221                 } else if (event.getLoggedInUser() == null) {
222                         // Throw NPE again
223                         throw new NullPointerException("event.loggedInUser is null"); //NOI18N
224                 } else if (event.getLoggedInUser().getUserId() == null) {
225                         // userId is null
226                         throw new NullPointerException("event.loggedInUser.userId is null"); //NOI18N
227                 } else if (event.getLoggedInUser().getUserId() < 1) {
228                         // Not avalid id
229                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
230                 }
231
232                 // Fill cache with all found user's receipts
233                 for (final BillableReceiptItem receiptItem : this.allReceiptItems) {
234                         // Is same user?
235                         if (Objects.equals(receiptItem.getItemReceipt().getReceiptUser(), event.getLoggedInUser())) {
236                                 // Yes, then add it
237                                 this.userReceiptItems.add(receiptItem);
238                         }
239                 }
240         }
241
242         @Override
243         public BillableReceiptItem findReceiptItemById (final Long receiptItemId) throws ReceiptItemNotFoundException {
244                 // Validate parameter
245                 if (null == receiptItemId) {
246                         // Throw NPE
247                         throw new NullPointerException("receiptItemId is null");
248                 } else if (receiptItemId < 1) {
249                         // Throw IAE
250                         throw new IllegalArgumentException(MessageFormat.format("receiptItemId={0} is not valid.", receiptItemId));
251                 }
252
253                 // Init instance
254                 BillableReceiptItem receiptItem = null;
255
256                 // Iterate over whole list
257                 for (final BillableReceiptItem currentReceiptItem : this.getAllReceiptItems()) {
258                         // Is the primary key matching?
259                         if (Objects.equals(currentReceiptItem.getItemId(), receiptItemId)) {
260                                 // Yes, then remember and exit iteration
261                                 receiptItem = currentReceiptItem;
262                                 break;
263                         }
264                 }
265
266                 // Is found?
267                 if (null == receiptItem) {
268                         // Not found
269                         throw new ReceiptItemNotFoundException(receiptItemId);
270                 }
271
272                 // Return it
273                 return receiptItem;
274         }
275
276         @Override
277         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
278         public List<BillableReceiptItem> getAllReceiptItems () {
279                 return this.allReceiptItems;
280         }
281
282         /**
283          * Getter for filtered receipt items
284          * <p>
285          * @return Filtered receipts
286          */
287         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
288         public List<BillableReceiptItem> getFilteredReceiptItems () {
289                 return this.filteredReceiptItems;
290         }
291
292         /**
293          * Setter for filtered receipt items
294          * <p>
295          * @param filteredReceiptItems Filtered receipt items
296          */
297         @SuppressWarnings ("AssignmentToCollectionOrArrayFieldFromParameter")
298         public void setFilteredReceiptItems (final List<BillableReceiptItem> filteredReceiptItems) {
299                 this.filteredReceiptItems = filteredReceiptItems;
300         }
301
302         /**
303          * Getter for selected receipt item
304          * <p>
305          * @return Selected receipt item
306          */
307         public BillableReceiptItem getSelectedReceiptItem () {
308                 return this.selectedReceiptItem;
309         }
310
311         /**
312          * Setter for selected receipt item
313          * <p>
314          * @param selectedReceiptItem Selected receipt item
315          */
316         public void setSelectedReceiptItem (final BillableReceiptItem selectedReceiptItem) {
317                 this.selectedReceiptItem = selectedReceiptItem;
318         }
319
320         @PostConstruct
321         public void initCache () {
322                 // Is cache there?
323                 if (!this.receiptItemCache.iterator().hasNext()) {
324                         // Add all
325                         for (final BillableReceiptItem receiptItem : this.receiptItemBean.fetchAllReceiptItems()) {
326                                 // Add it to cache
327                                 this.receiptItemCache.put(receiptItem.getItemId(), receiptItem);
328                         }
329                 }
330
331                 // Is the list empty, but filled cache?
332                 if (this.getAllReceiptItems().isEmpty() && this.receiptItemCache.iterator().hasNext()) {
333                         // Build up list
334                         for (final Cache.Entry<Long, BillableReceiptItem> currentEntry : this.receiptItemCache) {
335                                 // Add to list
336                                 this.getAllReceiptItems().add(currentEntry.getValue());
337                         }
338
339                         // Sort list
340                         this.getAllReceiptItems().sort(new Comparator<BillableReceiptItem>() {
341                                 @Override
342                                 public int compare (final BillableReceiptItem receiptItem1, final BillableReceiptItem receiptItem2) {
343                                         return receiptItem1.getItemId() > receiptItem2.getItemId() ? 1 : receiptItem1.getItemId() < receiptItem2.getItemId() ? -1 : 0;
344                                 }
345                         }
346                         );
347                 }
348         }
349
350         @Override
351         public boolean isReceiptItemAdded (final BillableReceiptItem receiptItem) {
352                 // Does it contain the same object?
353                 if (this.getAllReceiptItems().contains(receiptItem)) {
354                         // Yes, skip below code
355                         return true;
356                 }
357
358                 // Default is not the same
359                 boolean alreadyAdded = false;
360
361                 // Loop over all
362                 for (final BillableReceiptItem item : this.getAllReceiptItems()) {
363                         // Is the same?
364                         if (ReceiptItemUtils.isSameReceiptItem(item, receiptItem)) {
365                                 // Yes, found it
366                                 alreadyAdded = true;
367                                 break;
368                         }
369                 }
370
371                 // Return flag
372                 return alreadyAdded;
373         }
374
375         /**
376          * Uniquely add a receipt item instance.
377          * <p>
378          * @param receiptItem To be added/updated receipt item instance
379          */
380         private void uniqueAddReceiptItem (final BillableReceiptItem receiptItem) {
381                 // Add to cache and general list
382                 this.receiptItemCache.put(receiptItem.getItemId(), receiptItem);
383
384                 // Get iterator
385                 final Iterator<BillableReceiptItem> allIterator = this.getAllReceiptItems().iterator();
386
387                 // Iterate over all entries
388                 while (allIterator.hasNext()) {
389                         // Get current item
390                         final BillableReceiptItem currentReceiptItem = allIterator.next();
391
392                         // It the id matching?
393                         if (Objects.equals(receiptItem.getItemId(), currentReceiptItem.getItemId())) {
394                                 // Yes, then remove it and stop iterating
395                                 allIterator.remove();
396                                 break;
397                         }
398                 }
399
400                 // Re-add it
401                 this.getAllReceiptItems().add(receiptItem);
402
403                 // Is same user?
404                 if (this.userLoginController.isUserLoggedIn() && Objects.equals(receiptItem.getItemReceipt().getReceiptUser(), this.userLoginController.getLoggedInUser())) {
405                         // Get iterator
406                         final Iterator<BillableReceiptItem> userIterator = this.userReceiptItems.iterator();
407
408                         // Iterate over all entries
409                         while (userIterator.hasNext()) {
410                                 // Get current item
411                                 final BillableReceiptItem currentReceiptItem = userIterator.next();
412
413                                 // It the id matching?
414                                 if (Objects.equals(receiptItem.getItemId(), currentReceiptItem.getItemId())) {
415                                         // Yes, then remove it and stop iterating
416                                         userIterator.remove();
417                                         break;
418                                 }
419                         }
420
421                         // Re-add it
422                         this.userReceiptItems.add(receiptItem);
423                 }
424         }
425 }