-
Notifications
You must be signed in to change notification settings - Fork 4
/
FIN_Utility.java
1624 lines (1502 loc) · 65.5 KB
/
FIN_Utility.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.0 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2010-2015 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
*************************************************************************
*/
package org.openbravo.advpaymentmngt.utility;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.openbravo.advpaymentmngt.dao.AdvPaymentMngtDao;
import org.openbravo.advpaymentmngt.process.FIN_AddPayment;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.base.secureApp.VariablesSecureApp;
import org.openbravo.base.session.OBPropertiesProvider;
import org.openbravo.base.structure.BaseOBObject;
import org.openbravo.client.kernel.reference.UIDefinitionController;
import org.openbravo.dal.core.DalUtil;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.security.OrganizationStructureProvider;
import org.openbravo.dal.service.OBCriteria;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.data.FieldProvider;
import org.openbravo.erpCommon.utility.FieldProviderFactory;
import org.openbravo.erpCommon.utility.OBDateUtils;
import org.openbravo.erpCommon.utility.OBMessageUtils;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.model.ad.system.Client;
import org.openbravo.model.ad.utility.Sequence;
import org.openbravo.model.common.businesspartner.BusinessPartner;
import org.openbravo.model.common.currency.ConversionRate;
import org.openbravo.model.common.currency.ConversionRateDoc;
import org.openbravo.model.common.currency.Currency;
import org.openbravo.model.common.enterprise.DocumentType;
import org.openbravo.model.common.enterprise.Organization;
import org.openbravo.model.common.enterprise.OrganizationInformation;
import org.openbravo.model.common.invoice.Invoice;
import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
import org.openbravo.model.financialmgmt.payment.FIN_FinancialAccount;
import org.openbravo.model.financialmgmt.payment.FIN_Payment;
import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
import org.openbravo.model.financialmgmt.payment.FIN_PaymentMethod;
import org.openbravo.model.financialmgmt.payment.FIN_PaymentProposal;
import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
import org.openbravo.model.financialmgmt.payment.FinAccPaymentMethod;
import org.openbravo.service.db.CallStoredProcedure;
import org.openbravo.service.db.DbUtility;
import org.openbravo.utils.Replace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FIN_Utility {
private static final Logger log4j = LoggerFactory.getLogger(FIN_Utility.class);
private static AdvPaymentMngtDao dao;
/**
* @see OBDateUtils#getDate(String)
*/
public static Date getDate(String strDate) {
try {
return OBDateUtils.getDate(strDate);
} catch (ParseException e) {
log4j.error("Error parsing date", e);
return null;
}
}
/**
* @see OBDateUtils#getDateTime(String)
*/
public static Date getDateTime(String strDate) {
try {
return OBDateUtils.getDateTime(strDate);
} catch (ParseException e) {
log4j.error("Error parsing date", e);
return null;
}
}
/**
* Parses the string of comma separated id's to return a List object of the given class
*
* @param <T>
* @param t
* class of the OBObject the id's belong to
* @param _strSelectedIds
* String containing a comma separated list of id's
* @return a List object containing the parsed OBObjects
*/
public static <T extends BaseOBObject> List<T> getOBObjectList(Class<T> t, String _strSelectedIds) {
dao = new AdvPaymentMngtDao();
String strSelectedIds = _strSelectedIds;
final List<T> OBObjectList = new ArrayList<T>();
// selected scheduled payments list
if (strSelectedIds.startsWith("("))
strSelectedIds = strSelectedIds.substring(1, strSelectedIds.length() - 1);
if (!strSelectedIds.equals("")) {
strSelectedIds = Replace.replace(strSelectedIds, "'", "");
StringTokenizer st = new StringTokenizer(strSelectedIds, ",", false);
while (st.hasMoreTokens()) {
String strScheduledPaymentId = st.nextToken().trim();
OBObjectList.add(dao.getObject(t, strScheduledPaymentId));
}
}
return OBObjectList;
}
/**
*
* @param _strSelectedIds
* Identifiers string list with the following structure: ('ID', 'ID', 'ID')
* @return Map<K,V> using the ID as key and value <ID,ID> for each identifier.
*/
public static Map<String, String> getMapFromStringList(String _strSelectedIds) {
String strSelectedIds = _strSelectedIds;
final Map<String, String> map = new HashMap<String, String>();
if (strSelectedIds.startsWith("("))
strSelectedIds = strSelectedIds.substring(1, strSelectedIds.length() - 1);
if (!strSelectedIds.equals("")) {
strSelectedIds = Replace.replace(strSelectedIds, "'", "");
StringTokenizer st = new StringTokenizer(strSelectedIds, ",", false);
while (st.hasMoreTokens()) {
String strItem = st.nextToken().trim();
map.put(strItem, strItem);
}
}
return map;
}
/**
* Returns a FieldProvider object containing the Scheduled Payments.
*
* @param vars
* @param selectedScheduledPayments
* List of FIN_PaymentSchedule that need to be selected by default
* @param filteredScheduledPayments
* List of FIN_PaymentSchedule that need to unselected by default
*/
public static FieldProvider[] getShownScheduledPayments(VariablesSecureApp vars,
List<FIN_PaymentSchedule> selectedScheduledPayments,
List<FIN_PaymentSchedule> filteredScheduledPayments) {
final List<FIN_PaymentSchedule> shownScheduledPayments = new ArrayList<FIN_PaymentSchedule>();
shownScheduledPayments.addAll(selectedScheduledPayments);
shownScheduledPayments.addAll(filteredScheduledPayments);
FIN_PaymentSchedule[] FIN_PaymentSchedules = new FIN_PaymentSchedule[0];
FIN_PaymentSchedules = shownScheduledPayments.toArray(FIN_PaymentSchedules);
// FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(FIN_PaymentSchedules);
// FieldProvider[] data = new FieldProviderFactory[selectedScheduledPayments.size()];
FieldProvider[] data = FieldProviderFactory.getFieldProviderArray(shownScheduledPayments);
String dateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
.getProperty("dateFormat.java");
SimpleDateFormat dateFormater = new SimpleDateFormat(dateFormat);
// set in administrator mode to be able to access FIN_PaymentSchedule entity
OBContext.setAdminMode();
try {
for (int i = 0; i < data.length; i++) {
FieldProviderFactory.setField(data[i], "finSelectedPaymentId", (selectedScheduledPayments
.contains(FIN_PaymentSchedules[i])) ? FIN_PaymentSchedules[i].getId() : "");
FieldProviderFactory.setField(data[i], "finScheduledPaymentId",
FIN_PaymentSchedules[i].getId());
if (FIN_PaymentSchedules[i].getOrder() != null)
FieldProviderFactory.setField(data[i], "orderNr", FIN_PaymentSchedules[i].getOrder()
.getDocumentNo());
if (FIN_PaymentSchedules[i].getInvoice() != null) {
FieldProviderFactory.setField(data[i], "invoiceNr", FIN_PaymentSchedules[i].getInvoice()
.getDocumentNo());
FieldProviderFactory.setField(data[i], "invoicedAmount", FIN_PaymentSchedules[i]
.getInvoice().getGrandTotalAmount().toString());
}
FieldProviderFactory.setField(data[i], "dueDate",
dateFormater.format(FIN_PaymentSchedules[i].getDueDate()).toString());
FieldProviderFactory.setField(data[i], "expectedAmount", FIN_PaymentSchedules[i]
.getAmount().toString());
String strPaymentAmt = vars.getStringParameter(
"inpPaymentAmount" + FIN_PaymentSchedules[i].getId(), "");
FieldProviderFactory.setField(data[i], "paymentAmount", strPaymentAmt);
FieldProviderFactory.setField(data[i], "rownum", String.valueOf(i));
}
} finally {
OBContext.restorePreviousMode();
}
return data;
}
/**
* Creates a comma separated string with the Id's of the OBObjects included in the List.
*
* @param <T>
* @param obObjectList
* List of OBObjects
* @return Comma separated string of Id's
*/
@Deprecated
public static <T extends BaseOBObject> String getInStrList(List<T> obObjectList) {
return Utility.getInStrList(obObjectList);
}
/**
* Creates a comma separated string with the Id's of the Set of Strings. This method is deprecated
* as it has been added to Utility (core)
*
* @param set
* Set of Strings
* @return Comma separated string of Id's
*/
@Deprecated
public static String getInStrSet(Set<String> set) {
return Utility.getInStrSet(set);
}
/**
* Returns the cause of a trigger exception (BatchupdateException).
*
* Hibernate and JDBC will wrap the exception thrown by the trigger in another exception (the
* java.sql.BatchUpdateException) and this exception is sometimes wrapped again. Also the
* java.sql.BatchUpdateException stores the underlying trigger exception in the nextException and
* not in the cause property.
*
* @param t
* exception.
* @return the underlying trigger message.
*/
public static String getExceptionMessage(Throwable t) {
Throwable throwable = DbUtility.getUnderlyingSQLException(t);
return throwable.getMessage();
}
/**
* Returns the DocumentType defined for the Organization (or parent organization tree) and
* document category.
*
* @param org
* the Organization for which the Document Type is defined. The Document Type can belong
* to the parent organization tree of the specified Organization.
* @param docCategory
* the document category of the Document Type.
* @return the Document Type
*/
public static DocumentType getDocumentType(Organization org, String docCategory) {
DocumentType outDocType = null;
Client client = null;
if ("0".equals(org.getId())) {
client = OBContext.getOBContext().getCurrentClient();
if ("0".equals(client.getId())) {
return null;
}
} else {
client = org.getClient();
}
OBContext.setAdminMode(false);
try {
StringBuilder whereOrderByClause = new StringBuilder();
whereOrderByClause.append(" as dt where dt.organization.id in (");
whereOrderByClause.append(Utility.getInStrSet(new OrganizationStructureProvider()
.getParentTree(org.getId(), true)));
whereOrderByClause.append(") and dt.client.id = '" + client.getId()
+ "' and dt.documentCategory = '" + docCategory + "' order by ad_isorgincluded('"
+ org.getId() + "', dt.organization.id, '" + client.getId()
+ "') , dt.default desc, dt.id desc");
OBQuery<DocumentType> dt = OBDal.getInstance().createQuery(DocumentType.class,
whereOrderByClause.toString());
dt.setFilterOnReadableClients(false);
dt.setFilterOnReadableOrganization(false);
dt.setMaxResult(1);
List<DocumentType> dtList = dt.list();
if (dtList != null && !dtList.isEmpty()) {
outDocType = dtList.get(0);
}
} finally {
OBContext.restorePreviousMode();
}
return outDocType;
}
/**
* Returns the next sequence number of the Document Type defined for the Organization and document
* category. The current number of the sequence is also updated.
*
* @param docType
* Document type of the document
* @param tableName
* the name of the table from which the sequence will be taken if the Document Type does
* not have any sequence associated.
* @return the next sequence number of the Document Type defined for the Organization and document
* category. Null if no sequence is found.
*/
public static String getDocumentNo(DocumentType docType, String tableName) {
return getDocumentNo(docType, tableName, true);
}
/**
* Returns the next sequence number of the Document Type defined for the Organization and document
* category.
*
* @param docType
* Document type of the document
* @param tableName
* the name of the table from which the sequence will be taken if the Document Type does
* not have any sequence associated.
* @param updateNext
* Flag to update the current number of the sequence
* @return the next sequence number of the Document Type defined for the Organization and document
* category. Null if no sequence is found.
*/
public static String getDocumentNo(DocumentType docType, String tableName, boolean updateNext) {
String nextDocNumber = "";
if (docType != null) {
Sequence seq = docType.getDocumentSequence();
if (seq == null && tableName != null) {
OBCriteria<Sequence> obcSeq = OBDal.getInstance().createCriteria(Sequence.class);
obcSeq.add(Restrictions.eq(Sequence.PROPERTY_NAME, tableName));
obcSeq.setLockMode(LockMode.PESSIMISTIC_WRITE);
if (obcSeq != null && obcSeq.list().size() > 0) {
seq = obcSeq.list().get(0);
}
}
if (seq != null) {
if (seq.getPrefix() != null)
nextDocNumber = seq.getPrefix();
nextDocNumber += seq.getNextAssignedNumber().toString();
if (seq.getSuffix() != null)
nextDocNumber += seq.getSuffix();
if (updateNext) {
seq.setNextAssignedNumber(seq.getNextAssignedNumber() + seq.getIncrementBy());
OBDal.getInstance().save(seq);
// OBDal.getInstance().flush();
}
}
}
return nextDocNumber;
}
/**
* Returns the next sequence number of the Document Type defined for the Organization and document
* category. The current number of the sequence is also updated.
*
* @param org
* the Organization for which the Document Type is defined. The Document Type can belong
* to the parent organization tree of the specified Organization.
* @param docCategory
* the document category of the Document Type.
* @param tableName
* the name of the table from which the sequence will be taken if the Document Type does
* not have any sequence associated.
* @return the next sequence number of the Document Type defined for the Organization and document
* category. Null if no sequence is found.
*/
public static String getDocumentNo(Organization org, String docCategory, String tableName) {
DocumentType outDocType = getDocumentType(org, docCategory);
return getDocumentNo(outDocType, tableName, true);
}
/**
* Returns the next sequence number of the Document Type defined for the Organization and document
* category.
*
* @param org
* the Organization for which the Document Type is defined. The Document Type can belong
* to the parent organization tree of the specified Organization.
* @param docCategory
* the document category of the Document Type.
* @param tableName
* the name of the table from which the sequence will be taken if the Document Type does
* not have any sequence associated.
* @return the next sequence number of the Document Type defined for the Organization and document
* category. Null if no sequence is found.
*/
public static String getDocumentNo(Organization org, String docCategory, String tableName,
boolean updateNext) {
DocumentType outDocType = getDocumentType(org, docCategory);
return getDocumentNo(outDocType, tableName, updateNext);
}
/**
* Gets the available Payment Methods and returns in a String the html code containing all the
* Payment Methods in the natural tree of the given organization filtered by the Financial
* Account.
*
* @param strPaymentMethodId
* the Payment Method id that will be selected by default in case it is present in the
* list.
* @param strFinancialAccountId
* optional Financial Account id to filter the Payment Methods.
* @param strOrgId
* the Organization id the record belongs to.
* @param isMandatory
* boolean parameter to add an extra blank option if the drop-down is optional.
* @param excludePaymentMethodWithoutAccount
* if the strPaymentMethodId is empty or null then depending on this parameter the list
* will include payment methods with no Financial Accounts associated or only show the
* Payment Methods that belongs to at least on Financial Account
* @return a String with the html code with the options to fill the drop-down of Payment Methods.
*/
@Deprecated
public static String getPaymentMethodList(String strPaymentMethodId,
String strFinancialAccountId, String strOrgId, boolean isMandatory,
boolean excludePaymentMethodWithoutAccount) {
dao = new AdvPaymentMngtDao();
List<FIN_PaymentMethod> paymentMethods = dao.getFilteredPaymentMethods(strFinancialAccountId,
strOrgId, excludePaymentMethodWithoutAccount, AdvPaymentMngtDao.PaymentDirection.EITHER);
String options = getOptionsList(paymentMethods, strPaymentMethodId, isMandatory);
return options;
}
/**
* Gets the available Payment Methods and returns in a String the html code containing all the
* Payment Methods in the natural tree of the given organization filtered by the Financial
* Account.
*
* @param strPaymentMethodId
* the Payment Method id that will be selected by default in case it is present in the
* list.
* @param strFinancialAccountId
* optional Financial Account id to filter the Payment Methods.
* @param strOrgId
* the Organization id the record belongs to.
* @param isMandatory
* boolean parameter to add an extra blank option if the drop-down is optional.
* @param excludePaymentMethodWithoutAccount
* if the strPaymentMethodId is empty or null then depending on this parameter the list
* will include payment methods with no Financial Accounts associated or only show the
* Payment Methods that belongs to at least on Financial Account
* @param isInPayment
* specifies the type of payment to get payment methods for. If true, will return payment
* methods with Payment In enabled, if false will return payment methods with Payment Out
* enabled.
* @return a String with the html code with the options to fill the drop-down of Payment Methods.
*/
public static String getPaymentMethodList(String strPaymentMethodId,
String strFinancialAccountId, String strOrgId, boolean isMandatory,
boolean excludePaymentMethodWithoutAccount, boolean isInPayment) {
dao = new AdvPaymentMngtDao();
String selectedPaymentMethodId = strPaymentMethodId;
List<FIN_PaymentMethod> paymentMethods = dao.getFilteredPaymentMethods(strFinancialAccountId,
strOrgId, excludePaymentMethodWithoutAccount,
isInPayment ? AdvPaymentMngtDao.PaymentDirection.IN
: AdvPaymentMngtDao.PaymentDirection.OUT);
if ("".equals(selectedPaymentMethodId) && !"".equals(strFinancialAccountId)) {
selectedPaymentMethodId = dao.getDefaultPaymentMethodId(
OBDal.getInstance().get(FIN_FinancialAccount.class, strFinancialAccountId), isInPayment);
}
String options = getOptionsList(paymentMethods, selectedPaymentMethodId, isMandatory);
return options;
}
/**
* Gets the available Financial Accounts and returns in a String the html code containing all the
* Financial Accounts in the natural tree of the given organization filtered by the Payment
* Method.
*
* @param strPaymentMethodId
* optional Payment Method id to filter the Financial Accounts.
* @param strFinancialAccountId
* the Financial Account id that will be selected by default in case it is present in the
* list.
* @param strOrgId
* the Organization id the record belongs to.
* @param strCurrencyId
* optional Currency id to filter the Financial Accounts.
* @return a String with the html code with the options to fill the drop-down of Financial
* Accounts.
*/
@Deprecated
public static String getFinancialAccountList(String strPaymentMethodId,
String strFinancialAccountId, String strOrgId, boolean isMandatory, String strCurrencyId) {
List<FIN_FinancialAccount> financialAccounts = dao.getFilteredFinancialAccounts(
strPaymentMethodId, strOrgId, strCurrencyId, AdvPaymentMngtDao.PaymentDirection.EITHER);
String options = getOptionsList(financialAccounts, strFinancialAccountId, isMandatory);
return options;
}
/**
* Gets the available Financial Accounts and returns in a String the html code containing all the
* Financial Accounts in the natural tree of the given organization filtered by the Payment
* Method.
*
* @param strPaymentMethodId
* optional Payment Method id to filter the Financial Accounts.
* @param strFinancialAccountId
* the Financial Account id that will be selected by default in case it is present in the
* list.
* @param strOrgId
* the Organization id the record belongs to.
* @param strCurrencyId
* optional Currency id to filter the Financial Accounts.
* @param isInPayment
* specifies the type of payment to that is being made. If true, will return accounts
* with payment methods that have Payment In enabled, if false will return accounts with
* payment methods that have Payment Out enabled.
* @return a String with the html code with the options to fill the drop-down of Financial
* Accounts.
*/
public static String getFinancialAccountList(String strPaymentMethodId,
String strFinancialAccountId, String strOrgId, boolean isMandatory, String strCurrencyId,
boolean isInPayment) {
List<FIN_FinancialAccount> financialAccounts = dao.getFilteredFinancialAccounts(
strPaymentMethodId, strOrgId, strCurrencyId,
isInPayment ? AdvPaymentMngtDao.PaymentDirection.IN
: AdvPaymentMngtDao.PaymentDirection.OUT);
String options = getOptionsList(financialAccounts, strFinancialAccountId, isMandatory);
return options;
}
/**
* Returns a String containing the html code with the options based on the given List of
* BaseOBObjects
*
* @param <T>
* Class that extends BaseOBObject.
* @param obObjectList
* List containing the values to be included in the options.
* @param selectedValue
* value to set as selected by default.
* @param isMandatory
* boolean to add a blank option in the options list.
* @return a String containing the html code with the options. *
*/
public static <T extends BaseOBObject> String getOptionsList(List<T> obObjectList,
String selectedValue, boolean isMandatory) {
return getOptionsList(obObjectList, selectedValue, isMandatory, false);
}
/**
* Returns a String containing the html code with the options based on the given List of
* BaseOBObjects
*
* @param <T>
* Class that extends BaseOBObject.
* @param obObjectList
* List containing the values to be included in the options.
* @param selectedValue
* value to set as selected by default.
* @param isMandatory
* boolean to add a blank option in the options list.
* @param isRefList
* boolean to let know if the options belong to a refList. In that case, the value must
* be the search key of the list item instead of it's id.
* @return a String containing the html code with the options. *
*/
public static <T extends BaseOBObject> String getOptionsList(List<T> obObjectList,
String selectedValue, boolean isMandatory, boolean isRefList) {
StringBuilder strOptions = new StringBuilder();
if (!isMandatory)
strOptions.append("<option value=\"\"></option>");
for (T obObject : obObjectList) {
strOptions.append("<option value=\"")
.append((isRefList) ? obObject.getValue("searchKey") : obObject.getId()).append("\"");
if (obObject.getId().equals(selectedValue))
strOptions.append(" selected=\"selected\"");
strOptions.append(">");
strOptions.append(escape(obObject.getIdentifier()));
strOptions.append("</option>");
}
return strOptions.toString();
}
public static <T extends BaseOBObject> String getOptionsListFromFieldProvider(
FieldProvider[] fieldProvider, String selectedValue, boolean isMandatory) {
StringBuilder strOptions = new StringBuilder();
if (!isMandatory)
strOptions.append("<option value=\"\"></option>");
for (int i = 0; i < fieldProvider.length; i++) {
strOptions.append("<option value=\"").append(fieldProvider[i].getField("ID")).append("\"");
if (fieldProvider[i].getField("ID").equals(selectedValue))
strOptions.append(" selected=\"selected\"");
strOptions.append(">");
strOptions.append(escape(fieldProvider[i].getField("NAME")));
strOptions.append("</option>");
}
return strOptions.toString();
}
/**
* Method to replace special characters to print properly in an html. Changes are: ">" to ">"
* and "<" to "<"
*
* @param toEscape
* String to be replaced.
* @return the given String with the special characters replaced.
*/
private static String escape(String toEscape) {
String result = toEscape.replaceAll(">", ">");
result = result.replaceAll("<", "<");
return result;
}
/**
* Method used to calculate the Day still due for the payment.
*
* @param date
* . Due date of the payment.
* @return dayStillDue. Calculated Day Still due.
*/
public static Long getDaysToDue(Date date) {
final Date now = DateUtils.truncate(new Date(), Calendar.DATE);
return getDaysBetween(now, date);
}
/**
* Returns the amount of days between two given dates
*/
public static Long getDaysBetween(Date beginDate, Date endDate) {
final TimeZone tz = TimeZone.getDefault();
final long nowDstOffset = (tz.inDaylightTime(beginDate)) ? tz.getDSTSavings() : 0L;
final long dateDstOffset = (tz.inDaylightTime(endDate)) ? tz.getDSTSavings() : 0L;
return (endDate.getTime() + dateDstOffset - beginDate.getTime() - nowDstOffset)
/ DateUtils.MILLIS_PER_DAY;
}
public static boolean isAutomaticDepositWithdrawn(FIN_FinancialAccount account,
FIN_PaymentMethod paymentMethod, boolean isReceipt) {
FinAccPaymentMethod financialAccountPaymentMethod = new AdvPaymentMngtDao()
.getFinancialAccountPaymentMethod(account, paymentMethod);
if (financialAccountPaymentMethod == null)
return false;
return isReceipt ? financialAccountPaymentMethod.isAutomaticDeposit()
: financialAccountPaymentMethod.isAutomaticWithdrawn();
}
public static boolean isAutomaticDepositWithdrawn(FIN_Payment payment) {
return isAutomaticDepositWithdrawn(payment.getAccount(), payment.getPaymentMethod(),
payment.isReceipt());
}
public static boolean isAutomaticDepositWithdrawn(FIN_PaymentProposal paymentProposal) {
return isAutomaticDepositWithdrawn(paymentProposal.getAccount(),
paymentProposal.getPaymentMethod(), paymentProposal.isReceipt());
}
/**
* @see OBMessageUtils#messageBD(String)
*/
public static String messageBD(String strCode) {
return OBMessageUtils.messageBD(strCode);
}
/**
* Generic OBCriteria.
*
* @param clazz
* Class (entity).
* @param setFilterClient
* If true then only objects from readable clients are returned, if false then objects
* from all clients are returned
* @param setFilterOrg
* If true then when querying (for example call list()) a filter on readable
* organizations is added to the query, if false then this is not done
* @param values
* Value. Property, value and operator.
* @return All the records that satisfy the conditions.
*/
public static <T extends BaseOBObject> List<T> getAllInstances(Class<T> clazz,
boolean setFilterClient, boolean setFilterOrg, Value... values) {
OBCriteria<T> obc = OBDal.getInstance().createCriteria(clazz);
obc.setFilterOnReadableClients(setFilterClient);
obc.setFilterOnReadableOrganization(setFilterOrg);
for (Value value : values) {
if (value.getValue() == null && "==".equals(value.getOperator())) {
obc.add(Restrictions.isNull(value.getField()));
} else if (value.getValue() == null && "!=".equals(value.getOperator())) {
obc.add(Restrictions.isNotNull(value.getField()));
} else if ("==".equals(value.getOperator())) {
obc.add(Restrictions.eq(value.getField(), value.getValue()));
} else if ("!=".equals(value.getOperator())) {
obc.add(Restrictions.ne(value.getField(), value.getValue()));
} else if ("<".equals(value.getOperator())) {
obc.add(Restrictions.lt(value.getField(), value.getValue()));
} else if (">".equals(value.getOperator())) {
obc.add(Restrictions.gt(value.getField(), value.getValue()));
} else if ("<=".equals(value.getOperator())) {
obc.add(Restrictions.le(value.getField(), value.getValue()));
} else if (">=".equals(value.getOperator())) {
obc.add(Restrictions.ge(value.getField(), value.getValue()));
} else {
obc.add(Restrictions.eq(value.getField(), value.getValue()));
}
}
return obc.list();
}
/**
* Generic OBCriteria with filter on readable clients and organizations active.
*
* @param clazz
* Class (entity).
* @param values
* Value. Property, value and operator.
* @return All the records that satisfy the conditions.
*/
public static <T extends BaseOBObject> List<T> getAllInstances(Class<T> clazz, Value... values) {
return getAllInstances(clazz, true, true, values);
}
/**
* Generic OBCriteria.
*
* @param clazz
* Class (entity).
* @param values
* Value. Property, value and operator.
* @return One record that satisfies the conditions.
*/
public static <T extends BaseOBObject> T getOneInstance(Class<T> clazz, Value... values) {
OBCriteria<T> obc = OBDal.getInstance().createCriteria(clazz);
obc.setFilterOnReadableClients(false);
obc.setFilterOnReadableOrganization(false);
obc.add(Restrictions.ne(Client.PROPERTY_ID, "0"));
for (Value value : values) {
if (value.getValue() == null && "==".equals(value.getOperator())) {
obc.add(Restrictions.isNull(value.getField()));
} else if (value.getValue() == null && "!=".equals(value.getOperator())) {
obc.add(Restrictions.isNotNull(value.getField()));
} else if ("==".equals(value.getOperator())) {
obc.add(Restrictions.eq(value.getField(), value.getValue()));
} else if ("!=".equals(value.getOperator())) {
obc.add(Restrictions.ne(value.getField(), value.getValue()));
} else if ("<".equals(value.getOperator())) {
obc.add(Restrictions.lt(value.getField(), value.getValue()));
} else if (">".equals(value.getOperator())) {
obc.add(Restrictions.gt(value.getField(), value.getValue()));
} else if ("<=".equals(value.getOperator())) {
obc.add(Restrictions.le(value.getField(), value.getValue()));
} else if (">=".equals(value.getOperator())) {
obc.add(Restrictions.ge(value.getField(), value.getValue()));
} else {
obc.add(Restrictions.eq(value.getField(), value.getValue()));
}
}
final List<T> listt = obc.list();
if (listt != null && listt.size() > 0) {
return listt.get(0);
} else {
return null;
}
}
public static BigDecimal getDepositAmount(Boolean isReceipt, BigDecimal amount) {
BigDecimal deposit = BigDecimal.ZERO;
if (isReceipt) {
if (amount.compareTo(BigDecimal.ZERO) == 1) {
deposit = amount;
}
// else received payment was negative so treat as payment
} else {
if (amount.compareTo(BigDecimal.ZERO) == -1) {
// Negative payment out is a deposit
deposit = amount.abs();
}
}
return deposit;
}
public static BigDecimal getPaymentAmount(Boolean isReceipt, BigDecimal amount) {
BigDecimal payment = BigDecimal.ZERO;
if (isReceipt) {
if (amount.compareTo(BigDecimal.ZERO) == -1) {
// Negative payment in, treat as payment
payment = amount.abs();
}
} else {
if (amount.compareTo(BigDecimal.ZERO) == 1) {
payment = amount;
}
// else sent payment was negative so treat as deposit
}
return payment;
}
/**
* Convert a multi currency amount to a string for display in the UI. If amount has been converted
* to a different currency, then output that converted amount and currency as well
*
* @param amt
* Amount of payment
* @param currency
* Currency payment was made in
* @param convertedAmt
* Amount of payment in converted currency
* @param convertedCurrency
* Currency payment was converted to/from
* @return String version of amount formatted for display to user
*/
public static String multiCurrencyAmountToDisplay(BigDecimal amt, Currency currency,
BigDecimal convertedAmt, Currency convertedCurrency) {
StringBuffer out = new StringBuffer();
final UIDefinitionController.FormatDefinition formatDef = UIDefinitionController.getInstance()
.getFormatDefinition("euro", "Edition");
String formatWithDot = formatDef.getFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
try {
dfs.setDecimalSeparator(formatDef.getDecimalSymbol().charAt(0));
dfs.setGroupingSeparator(formatDef.getGroupingSymbol().charAt(0));
// Use . as decimal separator
final String DOT = ".";
if (!DOT.equals(formatDef.getDecimalSymbol())) {
formatWithDot = formatWithDot.replace(formatDef.getGroupingSymbol(), "@");
formatWithDot = formatWithDot.replace(formatDef.getDecimalSymbol(), ".");
formatWithDot = formatWithDot.replace("@", ",");
}
} catch (Exception e) {
// If any error use euroEdition default format
formatWithDot = "#0.00";
}
DecimalFormat amountFormatter = new DecimalFormat(formatWithDot, dfs);
amountFormatter.setMaximumFractionDigits(currency.getStandardPrecision().intValue());
out.append(amountFormatter.format(amt));
if (convertedCurrency != null && !currency.equals(convertedCurrency)
&& amt.compareTo(BigDecimal.ZERO) != 0) {
amountFormatter.setMaximumFractionDigits(convertedCurrency.getStandardPrecision().intValue());
out.append(" (").append(amountFormatter.format(convertedAmt)).append(" ")
.append(convertedCurrency.getISOCode()).append(")");
}
return out.toString();
}
/**
* Determine the conversion rate from one currency to another on a given date. Will use the spot
* conversion rate defined by the system for that date
*
* @param fromCurrency
* Currency to convert from
* @param toCurrency
* Currency being converted to
* @param conversionDate
* Date conversion is being performed
* @return A valid conversion rate for the parameters, or null if no conversion rate can be found
*/
public static ConversionRate getConversionRate(Currency fromCurrency, Currency toCurrency,
Date conversionDate, Organization org) {
java.util.List<ConversionRate> conversionRateList;
ConversionRate conversionRate;
OBContext.setAdminMode(true);
try {
final OBCriteria<ConversionRate> obcConvRate = OBDal.getInstance().createCriteria(
ConversionRate.class);
obcConvRate.setFilterOnReadableOrganization(false);
obcConvRate.add(Restrictions.eq(ConversionRate.PROPERTY_ORGANIZATION, org));
obcConvRate.add(Restrictions.eq(ConversionRate.PROPERTY_CURRENCY, fromCurrency));
obcConvRate.add(Restrictions.eq(ConversionRate.PROPERTY_TOCURRENCY, toCurrency));
obcConvRate.add(Restrictions.le(ConversionRate.PROPERTY_VALIDFROMDATE, conversionDate));
long oneDay = 24 * 60 * 60 * 1000;
obcConvRate.add(Restrictions.ge(ConversionRate.PROPERTY_VALIDTODATE,
new Date(conversionDate.getTime() - oneDay)));
conversionRateList = obcConvRate.list();
if ((conversionRateList != null) && (conversionRateList.size() != 0)) {
conversionRate = conversionRateList.get(0);
} else {
if ("0".equals(org.getId())) {
conversionRate = null;
} else {
return getConversionRate(
fromCurrency,
toCurrency,
conversionDate,
OBDal.getInstance().get(
Organization.class,
OBContext.getOBContext().getOrganizationStructureProvider()
.getParentOrg(org.getId())));
}
}
} catch (Exception e) {
log4j.error("Error getting conversion rate", e);
return null;
} finally {
OBContext.restorePreviousMode();
}
return conversionRate;
}
/**
* Determine the conversion rate from one currency to another on a given date and given
* documentId. Will use the spot conversion rate defined by the system for that date
*
* @param fromCurrency
* Currency to convert from
* @param toCurrency
* Currency being converted to
* @param documentId
* DocumentId to find the value in table c_conversion_rate_document
* @param entity
* Entity type of the document
* @return A valid conversion rate for the parameters, or null if no conversion rate can be found
*/
public static ConversionRateDoc getConversionRateDoc(Currency fromCurrency, Currency toCurrency,
String documentId, Entity entity) {
final OBCriteria<ConversionRateDoc> obcConvRateDoc = OBDal.getInstance().createCriteria(
ConversionRateDoc.class);
if (entity.equals(ModelProvider.getInstance().getEntity("Invoice"))) {
obcConvRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE, OBDal.getInstance()
.get(Invoice.class, documentId)));
} else if (entity.equals(ModelProvider.getInstance().getEntity("FIN_Payment"))) {
obcConvRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_PAYMENT, OBDal.getInstance()
.get(FIN_Payment.class, documentId)));
} else if (entity.equals(ModelProvider.getInstance().getEntity("FIN_Finacc_Transaction"))) {
obcConvRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_FINANCIALACCOUNTTRANSACTION,
OBDal.getInstance().get(FIN_FinaccTransaction.class, documentId)));
}
obcConvRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, fromCurrency));
obcConvRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, toCurrency));
obcConvRateDoc.setMaxResults(1);
if (obcConvRateDoc.uniqueResult() != null) {
return (ConversionRateDoc) obcConvRateDoc.uniqueResult();
} else
return null;
}
public static int getConversionRatePrecision(VariablesSecureApp vars) {
try {
String formatOutput = vars
.getSessionValue("#FormatOutput|generalQtyRelation", "#,##0.######");
String decimalSeparator = ".";
if (formatOutput.contains(decimalSeparator)) {
formatOutput = formatOutput.substring(formatOutput.indexOf(decimalSeparator),
formatOutput.length());
return formatOutput.length() - decimalSeparator.length();
} else {
return 0;
}
} catch (Exception e) {
log4j.error("Error getting conversion rate precission", e);
return 6; // by default precision of 6 decimals as is defaulted in Format.xml
}
}
/**
* Formats a number using the given format, decimal and grouping separator.
*
* @param number
* Number to be formatted.
* @param javaFormat
* Java number format pattern.
* @param _decimalSeparator
* Symbol used as decimal separator.
* @param _groupingSeparator
* Symbol used as grouping separator.
* @return Formatted string.
*/
public static String formatNumber(BigDecimal number, String javaFormat, String _decimalSeparator,
String _groupingSeparator) {
if (StringUtils.isEmpty(javaFormat)) {
return formatNumber(number);
}
String decimalSeparator = _decimalSeparator;
String groupingSeparator = _groupingSeparator;
if (StringUtils.isEmpty(decimalSeparator) || StringUtils.isEmpty(groupingSeparator)) {
decimalSeparator = ".";