-
Notifications
You must be signed in to change notification settings - Fork 4
/
Reports.cs
2749 lines (2567 loc) · 105 KB
/
Reports.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Reflection;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CodeFirstWebFramework;
namespace AccountServer {
[Auth(AccessLevel.ReadOnly)]
public class Reports : AppModule {
public enum DateRange {
All = 1,
Today,
ThisWeek,
ThisMonth,
ThisQuarter,
ThisYear,
Yesterday,
LastWeek,
LastMonth,
LastQuarter,
LastYear,
Custom,
NDays,
NMonths,
}
/// <summary>
/// Fields which can be displayed in the report
/// </summary>
List<ReportField> _fields;
/// <summary>
/// Filters which can be applied
/// </summary>
List<Filter> _filters;
/// <summary>
/// Sort orders which can be chosen
/// </summary>
JArray _sortOrders;
/// <summary>
/// Sort order split into fields
/// </summary>
string[] _sortFields;
/// <summary>
/// Whether change type required in Audit reports
/// </summary>
bool _changeTypeNotRequired;
/// <summary>
/// All reports have a date filter
/// </summary>
DateFilter _dates;
[Writeable]
public class ReportSettings : JsonObject {
/// <summary>
/// Sort order to use
/// </summary>
public string SortBy;
public bool DescendingOrder;
/// <summary>
/// How/whether to total (0 = none, 1 = data & totals, 2 = totals only)
/// </summary>
public int Totalling;
/// <summary>
/// Whether to show a grand total (not, e.g., for the VAT detail report!)
/// </summary>
public bool GrandTotal = true;
/// <summary>
/// Whether to split lines
/// </summary>
[Field(Heading = "Compact to save paper")]
public bool Split;
/// <summary>
/// Reverse sign in journal reports
/// </summary>
[Field(Heading = "Reverse sign of amounts")]
public bool ReverseSign;
public int PeriodLength = 1;
}
ReportSettings _settings = new ReportSettings();
string _settingsRequired = "SortBy,DescendingOrder,Totalling,GrandTotal,Split";
public object ReportList;
/// <summary>
/// Reports menu
/// </summary>
public override void Default() {
SessionData.Report = new JObject();
Dictionary<string, List<JObject>> groups = new Dictionary<string, List<JObject>>();
groups["Memorised Reports"] = new List<JObject>();
List<JObject> reports = new List<JObject>();
addReport(reports, new JObject().AddRange("ReportName", "Document Report", "ReportType", "Documents", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Transaction Report", "ReportType", "Transactions", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Journals Report", "ReportType", "Journals", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Profit and Loss", "ReportType", "ProfitAndLoss", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Balance Sheet", "ReportType", "BalanceSheet", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Trial Balance", "ReportType", "TrialBalance", "idReport", 0));
if(Settings.RecordVat)
addReport(reports, new JObject().AddRange("ReportName", "VAT Detail Report", "ReportType", "VatDetail", "idReport", 0));
if(Settings.Customers || Settings.Suppliers)
addReport(reports, new JObject().AddRange("ReportName", "Ageing Report", "ReportType", "Ageing", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Cashflow Report", "ReportType", "Cashflow", "idReport", 0));
groups["Standard Reports"] = reports;
reports = new List<JObject>();
addReport(reports, new JObject().AddRange("ReportName", "Accounts List", "ReportType", "Accounts", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Names List", "ReportType", "Names", "idReport", 0));
if(Settings.Members)
addReport(reports, new JObject().AddRange("ReportName", "Members List", "ReportType", "Members", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Products List", "ReportType", "Products", "idReport", 0));
if (Settings.RecordVat)
addReport(reports, new JObject().AddRange("ReportName", "VAT Codes List", "ReportType", "VatCodes", "idReport", 0));
if (Settings.Investments)
addReport(reports, new JObject().AddRange("ReportName", "Securities List", "ReportType", "Securities", "idReport", 0));
if (SecurityOn)
addReport(reports, new JObject().AddRange("ReportName", "Users List", "ReportType", "Users", "idReport", 0));
groups["Lists"] = reports;
reports = new List<JObject>();
addReport(reports, new JObject().AddRange("ReportName", "Audit Transactions Report", "ReportType", "AuditTransactions", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Audit Accounts Report", "ReportType", "AuditAccounts", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Audit Names Report", "ReportType", "AuditNames", "idReport", 0));
if (Settings.Members)
addReport(reports, new JObject().AddRange("ReportName", "Audit Members Report", "ReportType", "AuditMembers", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Audit Products Report", "ReportType", "AuditProducts", "idReport", 0));
if (Settings.RecordVat)
addReport(reports, new JObject().AddRange("ReportName", "Audit VAT Codes Report", "ReportType", "AuditVatCodes", "idReport", 0));
if (Settings.Investments)
addReport(reports, new JObject().AddRange("ReportName", "Audit Securities Report", "ReportType", "AuditSecurities", "idReport", 0));
if (SecurityOn)
addReport(reports, new JObject().AddRange("ReportName", "Audit Users", "ReportType", "AuditUsers", "idReport", 0));
addReport(reports, new JObject().AddRange("ReportName", "Reconciliation Report", "ReportType", "AuditReconciliation", "idReport", 0));
groups["Audit Reports"] = reports;
foreach (JObject report in Database.Query("SELECT idReport, ReportGroup, ReportName, ReportType FROM Report WHERE Chart = 0 ORDER BY ReportGroup, ReportName").ToList()) {
string group = report.AsString("ReportGroup");
if (!groups.TryGetValue(group, out reports)) {
reports = new List<JObject>();
groups[group] = reports;
}
addReport(reports, report);
}
ReportList = groups;
}
void addReport(List<JObject> reports, JObject report) {
if(HasAccess(Info, report.AsString("ReportType").ToLower(), out int accessLevel))
reports.Add(report);
}
public void Accounts(int id) {
Record = AccountsSave(getJson(id, "Accounts List"));
}
public object AccountsSave(JObject json) {
initialiseReport(json);
accountSetup();
setDefaultFields(json, "AccountName", "AccountDescription", "AcctType");
makeSortable("AccountName", "AcctType", "AccountCode,AccountName=AccountCode");
return finishReport(json, "Account", "AccountName", "LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId");
}
void accountSetup() {
addTable("Account");
addTable("AccountType", "idAccountType", "AcctType");
fieldFor("idAccountType").MakeEssential().Hide();
_filters.Add(new StringFilter("AccountName", "Account.AccountName"));
_filters.Add(new StringFilter("AccountDescription", "Account.AccountDescription"));
_filters.Add(new RecordFilter("AccountType", "Account.AccountTypeId", SelectAccountTypes()));
}
public void AuditAccounts(int id) {
Record = AuditAccountsSave(getJson(id, "Accounts Audit Report"));
Method = "accounts";
}
public object AuditAccountsSave(JObject json) {
initialiseAuditReport(json);
accountSetup();
return auditReportData(json, "Account", "AccountName", "AccountDescription", "AcctType");
}
/// <summary>
/// Audit history of an arbitrary record in an arbitrary table
/// </summary>
public void AuditHistory(string table, int id) {
Utils.Check(id > 0, "Invalid record id {0}", id);
JObject json = new JObject().AddRange(
"ReportName", "Audit trail",
"ReportType", "Audit" + table,
"idReport", null,
"recordId", id);
Record = AuditHistorySave(json);
}
public object AuditHistorySave(JObject json) {
OriginalMethod = json.AsString("ReportType");
Method = OriginalMethod.Substring(5).ToLower();
MethodInfo method = this.GetType().GetMethod(OriginalMethod + "Save", BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
Utils.Check(method != null, "Invalid table {0}", Method);
return method.Invoke(this, new object[] { json });
}
public void AuditNames(int id) {
Record = AuditNamesSave(getJson(id, "Names Audit Report"));
Method = "names";
}
public object AuditNamesSave(JObject json) {
initialiseAuditReport(json);
namesSetup();
return auditReportData(json, "NameAddress", "Type", "Name", "Address", "PostCode", "Telephone", "Email", "Contact");
}
public void AuditMembers(int id) {
Record = AuditMembersSave(getJson(id, "Members Audit Report"));
Method = "members";
}
public object AuditMembersSave(JObject json) {
initialiseAuditReport(json);
membersSetup();
return auditReportData(json, "Full_Member", "MemberTypeName", "MemberNo", "Title", "FirstName", "LastName", "Address", "PostCode", "Telephone", "Email", "Contact", "AnnualSubscription", "PaymentAmount", "AmountDue");
}
public void AuditProducts(int id) {
Record = AuditProductsSave(getJson(id, "Products Audit Report"));
Method = "products";
}
public object AuditProductsSave(JObject json) {
initialiseAuditReport(json);
addTable("Product");
addTable("Account", "AccountName");
addTable("VatCode");
_filters.Add(new StringFilter("ProductName", "Product.ProductName"));
_filters.Add(new StringFilter("ProductDescription", "Product.ProductDescription"));
_filters.Add(new DecimalFilter("UnitPrice", "Product.UnitPrice"));
return auditReportData(json, "Product", "ProductName", "ProductDescription", "UnitPrice", "Code", "AccountName");
}
public void AuditSecurities(int id) {
Record = AuditSecuritiesSave(getJson(id, "Securities Audit Report"));
Method = "securities";
}
public object AuditSecuritiesSave(JObject json) {
initialiseAuditReport(json);
addTable("Security");
_filters.Add(new StringFilter("SecurityName", "Security.SecurityName"));
_filters.Add(new StringFilter("Ticker", "Security.Ticker"));
return auditReportData(json, "Security", "SecurityName", "Ticker");
}
[Auth(AccessLevel.Admin, Hide = true)]
public void AuditUsers(int id) {
Record = AuditUsersSave(getJson(id, "Users Audit Report"));
Method = "users";
}
public object AuditUsersSave(JObject json) {
initialiseAuditReport(json);
addTable("User");
addTable("Permission");
RemoveField("Password");
var levelSelect = Server.NamespaceDef.GetAccessLevel().Select();
fieldFor("AccessLevel").MakeSelectable(levelSelect);
fieldFor("FunctionAccessLevel").MakeSelectable(levelSelect);
_filters.Add(new StringFilter("Login", "User.Login"));
_filters.Add(new StringFilter("Email", "User.Email"));
_filters.Add(new RecordFilter("AccessLevel", "User.AccessLevel", levelSelect));
return auditReportData(json, "User", "Login", "Email", "AccessLevel", "ModulePermissions");
}
public void AuditReconciliation(int id) {
Record = AuditReconciliationSave(getJson(id, "Reconciliation Report"));
Method = "transactions";
}
public object AuditReconciliationSave(JObject json) {
// Not looking at changes - reconciliations are stored as created
_changeTypeNotRequired = true;
initialiseAuditReport(json);
addTable("!Account", "AccountName", "AccountDescription", "EndingBalance");
_fields.Add(new ReportField("OpeningBalance", "decimal", "Opening Balance") { Table = "Account" });
_fields.Add(new ReportField("ClearedBalance", "decimal", "Cleared Balance") { Table = "Account" });
addTable("Extended_Document", "idDocument", "DocumentDate", "DocumentIdentifier", "DocumentName", "DocumentAddress", "DocumentAmount", "DocumentOutstanding", "DocType", "DocumentTypeId");
fieldFor("DocumentTypeId").MakeEssential().Hide();
addTable("Journal", "Amount", "Cleared");
fieldFor("Cleared")["type"] = "checkbox";
_filters.Add(new RecordFilter("Account", "idAccount", SelectBankOrOtherALAccounts()));
_filters.Add(new StringFilter("AccountCode", "AccountCode"));
_settings.Split = true;
return auditReportData(json, "Reconciliation", "AccountName", "OpeningBalance", "EndingBalance", "ClearedBalance", "DocumentDate", "DocType", "DocumentIdentifier", "DocumentName", "Cleared", "Amount");
}
public void AuditTransactions(int id) {
Record = AuditTransactionsSave(getJson(id, "Transactions Audit Report"));
Method = "transactions";
}
public object AuditTransactionsSave(JObject json) {
initialiseAuditReport(json);
addTable("Extended_Document", "idDocument", "DocumentDate", "DocumentIdentifier", "DocumentName", "DocumentAddress", "DocumentAmount", "DocumentOutstanding", "DocType", "DocumentTypeId", "DocumentMemo");
fieldFor("DocumentTypeId").MakeEssential().Hide();
addTable("Journal");
addTable("Account", "AccountName");
addTable("NameAddress", "Name");
addTable("VatCode", "Code");
addTable("Line");
addTable("Product", "ProductName");
_filters.Add(new DateFilter(Settings, "DocumentDate", DateRange.All));
_filters.Add(new StringFilter("Id", "DocumentIdentifier"));
_filters.Add(new DecimalFilter("DocumentAmount", "Extended_Document.DocumentAmount"));
_filters.Add(new DecimalFilter("DocumentOutstanding", "Extended_Document.DocumentOutstanding"));
_filters.Add(new RecordFilter("DocumentType", "DocumentTypeId", SelectDocumentTypes()));
_filters.Add(new RecordFilter("Account", "Journal.AccountId", SelectAccounts()));
_filters.Add(new StringFilter("AccountCode", "AccountCode"));
_filters.Add(new RecordFilter("NameAddress", "Journal.NameAddressId", SelectNames()));
_filters.Add(new RecordFilter("VatCode", "Line.VatCodeId", SelectVatCodes()));
_filters.Add(new RecordFilter("Product", "Line.ProductId", SelectProducts()));
_filters.Add(new DecimalFilter("JournalAmount", "Journal.Amount"));
_filters.Add(new StringFilter("Memo", "Journal.Memo"));
_settings.Split = true;
return auditReportData(json, "Document", "idDocument", "DocType", "DocumentDate", "Name", "DocumentIdentifier", "DocumentAmount", "DocumentOutstanding", "AccountName", "Debit", "Credit", "Qty", "Memo", "Code", "VatRate", "VatAmount");
}
public void AuditVatCodes(int id) {
Record = AuditVatCodesSave(getJson(id, "VAT Codes Audit Report"));
Method = "vatcodes";
}
public object AuditVatCodesSave(JObject json) {
initialiseAuditReport(json);
vatCodeSetup();
return auditReportData(json, "Code", "VatDescription", "Rate");
}
/// <summary>
/// Ageing report splits outstdanding debt by date
/// </summary>
public void Ageing(int id) {
Record = AgeingSave(getJson(id, "Ageing Report"));
}
public object AgeingSave(JObject json) {
initialiseReport(json);
// Can select Sales or Purchases
JObject [] accountSelect = new JObject[] {
new JObject().AddRange("id", (int)Acct.SalesLedger, "value", "Sales Ledger"),
new JObject().AddRange("id", (int)Acct.PurchaseLedger, "value", "Purchase Ledger")
};
ReportField acct = new ReportField("AccountId", "select", "Account");
acct["selectOptions"] = new JArray(accountSelect);
acct.Essential = true;
_fields.Add(acct);
_fields.Add(new ReportField("NameAddressId", "int", "NameAddressId").Hide().MakeEssential());
_fields.Add(new ReportField("Name", "string", "Name"));
// Fields for each ageing bucket
_fields.Add(new ReportField("SUM(CASE WHEN age BETWEEN 0 AND 29 THEN Outstanding ELSE 0 END) AS Current", "decimal", "Current"));
for(int i = 1; i < 90; i += 30)
_fields.Add(new ReportField("SUM(CASE WHEN age BETWEEN " + (i + 29) + " AND " + (i + 58) + " THEN Outstanding ELSE 0 END) AS b" + i, "decimal", i + "-" + (i + 29)));
_fields.Add(new ReportField("SUM(CASE WHEN age > 120 THEN Outstanding ELSE 0 END) AS old", "decimal", ">90"));
_fields.Add(new ReportField("SUM(Outstanding) AS Total", "decimal", "Total"));
RecordFilter account = new RecordFilter("Account", "Journal.AccountId", accountSelect) {
Apply = false
};
_filters.Add(account);
_settingsRequired = "";
_settings.SortBy = "";
_settings.Totalling = 1;
setDefaultFields(json, "AccountId", "Name", "Current", "b1", "b31", "b61", "old", "Total");
readSettings(json); // we need account filter value setting now
string where = account.Active ? account.Where(Database) : "AccountId IN (1, 2)";
return finishReport(json, @"(SELECT AccountId, NameAddressId, Name, Outstanding,
DATEDIFF(" + Database.Quote(Utils.Today) + @", DocumentDate) AS age
FROM Journal
JOIN Document ON idDocument = DocumentId
JOIN NameAddress ON idNameAddress = NameAddressId
WHERE " + where + @"
AND Type IN('S', 'C')
AND Outstanding <> 0
) AS DaysDue", "AccountId,Name",
"GROUP BY AccountId, Name");
}
public void BalanceSheet(int id) {
Record = BalanceSheetSave(getJson(id, "Balance Sheet"));
}
public object BalanceSheetSave(JObject json) {
_settings.Totalling = 0;
_settings.GrandTotal = false;
initialiseReport(json);
addTable("!AccountType");
addTable("Account", "idAccount", "AccountCode", "AccountName", "AccountDescription");
fieldFor("idAccount").Hide();
fieldFor("AccountName")["sClass"] = "sa";
fieldFor("Heading").MakeEssential();
fieldFor("Negate").MakeEssential().Hide();
fieldFor("BalanceSheet").MakeEssential().Hide();
DateFilter date = new DateFilter(Settings, "DocumentDate", DateRange.LastYear);
ReportField cp = new ReportField("CurrentPeriod", "decimal", "Current Period");
_fields.Add(cp);
ReportField lp = new ReportField("PreviousPeriod", "decimal", "Previous Period");
_fields.Add(lp);
_filters.Add(date);
setDefaultFields(json, "Heading", "AcctType", "AccountName", "CurrentPeriod", "PreviousPeriod");
_settingsRequired = "";
_settings.SortBy = "AcctType";
readSettings(json);
// Balance sheet needs 2 period buckets for the 2 columns
DateTime[] cPeriod = date.CurrentPeriod();
cp["heading"] = date.PeriodName(cPeriod);
DateTime[] lPeriod = date.PreviousPeriod();
lp["heading"] = date.PeriodName(lPeriod);
string[] sort = new string[] { "AccountTypeId", "AccountCode", "AccountName" };
string[] fields = _fields.Where(f => f.Include || f.Essential || _sortFields.Contains(f.Name)).Select(f => f.FullFieldName).Distinct().ToArray();
// We want one record per account, with totals for each bucket, and an Old value
// which is sum of all transactions before first bucket (opening balance)
JObjectEnumerable report = Database.Query("SELECT " + string.Join(",", fields) + @", Old
FROM AccountType
LEFT JOIN Account ON Account.AccountTypeId = AccountType.idAccountType
JOIN (SELECT AccountId,
SUM(CASE WHEN DocumentDate < " + Database.Quote(cPeriod[1]) + " AND DocumentDate >= " + Database.Quote(cPeriod[0]) + @" THEN Amount ELSE 0 END) AS CurrentPeriod,
SUM(CASE WHEN DocumentDate < " + Database.Quote(lPeriod[1]) + " AND DocumentDate >= " + Database.Quote(lPeriod[0]) + @" THEN Amount ELSE 0 END) AS PreviousPeriod,
SUM(CASE WHEN DocumentDate < " + Database.Quote(lPeriod[0]) + @" THEN Amount ELSE 0 END) AS Old
FROM Journal
LEFT JOIN Document ON Document.idDocument = Journal.DocumentId
WHERE DocumentDate < " + Database.Quote(cPeriod[1]) + @"
GROUP BY AccountId
) AS Summary ON AccountId = idAccount
ORDER BY " + string.Join(",", sort.Select(s => s + (_settings.DescendingOrder ? " DESC" : "")).ToArray())
);
_sortFields = new string[] { "Heading", "AcctType", "AccountCode", "AccountName" };
// Report now needs further processing to:
// Calculate retained earnings account
// Add investment gains
// Consolidate P & L accounts and produce totals
return reportJson(json, fixBalanceSheet(addInvestmentGains(addRetainedEarnings(report), "Old", lPeriod[0], "PreviousPeriod", cPeriod[0], "CurrentPeriod", cPeriod[1])), "AccountType", "Account");
}
public void Documents(int id) {
Record = DocumentsSave(getJson(id, "Documents Report"));
Method = "transactions";
}
public object DocumentsSave(JObject json) {
initialiseReport(json);
addTable("Extended_Document");
fieldFor("DocumentTypeId").MakeEssential().Hide();
fieldFor("DocumentNameAddressId").Hide();
fieldFor("DocumentAccountId").Hide();
addTable("NameAddress", "Type", "Telephone", "Email", "Contact");
fieldFor("Type").MakeSelectable(SelectNameTypes());
_filters.Add(new DateFilter(Settings, "DocumentDate", DateRange.ThisMonth));
_filters.Add(new StringFilter("Id", "DocumentIdentifier"));
_filters.Add(new DecimalFilter("DocumentAmount", "Extended_Document.DocumentAmount"));
_filters.Add(new DecimalFilter("DocumentOutstanding", "Extended_Document.DocumentOutstanding"));
_filters.Add(new RecordFilter("DocumentType", "DocumentTypeId", SelectDocumentTypes()));
_filters.Add(new RecordFilter("NameAddress", "DocumentNameAddressId", SelectNames()));
_filters.Add(new StringFilter("DocumentMemo", "DocumentMemo"));
makeSortable("idDocument=Trans no", "DocumentDate", "DocumentIdentifier=Doc Id", "Type,DocumentName=Document Name", "DocumentAmount", "DocType");
setDefaultFields(json, "idDocument", "DocType", "DocumentDate", "DocumentName", "DocumentIdentifier", "DocumentAmount", "DocumentOutstanding");
return finishReport(json, "Extended_Document", "idDocument", "LEFT JOIN NameAddress ON NameAddress.idNameAddress = DocumentNameAddressId",
"Extended_Document");
}
public void Journals(int id) {
Record = JournalsSave(getJson(id, "Journals Report"));
}
public object JournalsSave(JObject json) {
initialiseReport(json);
addTable("AccountType");
fieldFor("idAccountType").Hide().Essential = false;
addTable("Account", "idAccount", "AccountCode", "AccountName", "AccountDescription");
addTable("!Journal");
_fields.Add(new ReportField("Vat", "decimal", "Vat"));
_fields.Add(new ReportField("Result.Amount + Result.Vat AS Gross", "decimal", "Gross"));
addTable("!NameAddress");
addTable("Document", "idDocument", "DocumentDate", "DocumentIdentifier", "DocumentTypeId", "DocumentMemo");
fieldFor("idDocument").MakeEssential();
addTable("DocumentType", "DocType");
fieldFor("DocumentDate").FullFieldName = "rDocDate AS DocumentDate";
fieldFor("DocumentTypeId").MakeEssential().Hide().FullFieldName = "rDocType AS DocumentTypeId";
fieldFor("Amount").FullFieldName = "Result.Amount";
fieldFor("Credit").FullFieldName = "Result.Amount";
fieldFor("Debit").FullFieldName = "Result.Amount";
fieldFor("idAccount").Hide().Essential = true;
DateFilter date = new DateFilter(Settings, "DocumentDate", DateRange.ThisMonth);
RecordFilter account = new RecordFilter("Account", "Journal.AccountId", SelectAccounts());
date.Apply = false;
account.Apply = false;
_filters.Add(date);
_filters.Add(account);
_filters.Add(new RecordFilter("AccountType", "Account.AccountTypeId", SelectAccountTypes()));
_filters.Add(new StringFilter("Id", "DocumentIdentifier"));
_filters.Add(new RecordFilter("DocumentType", "DocumentTypeId", SelectDocumentTypes()));
_filters.Add(new RecordFilter("NameAddress", "Journal.NameAddressId", SelectNames()));
_filters.Add(new DecimalFilter("JournalAmount", "Result.Amount"));
_filters.Add(new StringFilter("Memo", "Journal.Memo"));
_settingsRequired += ",ReverseSign";
makeSortable("idAccountType,AcctType,AccountCode,AccountName=Account Type", "AccountName", "AccountCode,AccountName=AccountCode", "Name", "DocumentDate", "DocumentIdentifier=Doc Id", "DocType");
setDefaultFields(json, "AcctType", "AccountName", "Amount", "Memo", "Name", "DocType", "DocumentDate", "DocumentIdentifier");
readSettings(json); // we need account filter now!
string where = account.Active ? "\r\nAND " + account.Where(Database) : "";
// Need opening balance before start of period
// Journals in period
// Security gains/losses
List<JObject> report = finishReport(@"(
SELECT * FROM
(SELECT Account.idAccount AS rAccount, Account.AccountTypeId as rAcctType, SUM(Journal.Amount) AS Amount, 0 AS Vat, " + (int)DocType.OpeningBalance + " AS rDocType, 0 as rJournal, 0 as rDocument, 0 AS rJournalNum, "
+ Database.Cast(Database.Quote(date.CurrentPeriod()[0]), "DATETIME") + @" AS rDocDate
FROM Account
LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId
LEFT JOIN Journal ON Journal.AccountId = Account.idAccount
LEFT JOIN Document ON Document.idDocument = Journal.DocumentId
WHERE DocumentDate < " + Database.Quote(date.CurrentPeriod()[0]) + @"
AND BalanceSheet = 1" + where + @"
GROUP BY AccountName) AS OpeningBalances
WHERE Amount <> 0 OR rAcctType IN (" + (int)AcctType.Investment + "," + (int)AcctType.Security + @")
UNION
SELECT Account.idAccount AS rAccount, Account.AccountTypeId as rAcctType, Journal.Amount, IFNULL(DocumentType.Sign * Line.VatAmount, 0) AS Vat, DocumentTypeId As rDocType, idJournal AS rJournal, idDocument as rDocument,
JournalNum as rJournal, DocumentDate AS rDocDate
FROM Account
LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId
LEFT JOIN Journal ON Journal.AccountId = Account.idAccount
LEFT JOIN Line ON Line.idLine = Journal.idJournal
LEFT JOIN Document ON Document.idDocument = Journal.DocumentId
LEFT JOIN DocumentType ON DocumentType.idDocumentType = Document.DocumentTypeId
WHERE " + date.Where(Database) + where + @"
UNION
SELECT Account.idAccount AS rAccount, Account.AccountTypeId as rAcctType, 0 AS Amount, 0 AS Vat, " + (int)DocType.Gain + " AS rDocType, 0 as rJournal, 0 as rDocument, 0 AS rJournalNum, "
+ Database.Cast(Database.Quote(date.CurrentPeriod()[1].AddDays(-1)), "DATETIME") + @" AS rDocDate
FROM Account
WHERE AccountTypeId = " + (int)AcctType.Security + where.Replace("Journal.AccountId", "idAccount") + @"
) AS Result", "idAccountType,AcctType,AccountCode,AccountName,,DocumentDate,idDocument,JournalNum", @"
LEFT JOIN Account on Account.idAccount = rAccount
LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId
LEFT JOIN Journal ON Journal.idJournal = rJournal
LEFT JOIN NameAddress ON NameAddress.idNameAddress = Journal.NameAddressId
LEFT JOIN Document ON Document.idDocument = rDocument
LEFT JOIN DocumentType ON DocumentType.idDocumentType = rDocType
", json).ToList();
return reportJson(json, addInvestmentGains(date.CurrentPeriod(), account, report), "Account", "AccountType");
}
string periodFromDate(DateTime date) {
switch (_settings.PeriodLength) {
case 0: // Weekly
// ISO week number is based on a Thursday
int increment = 0;
switch (date.DayOfWeek) {
case DayOfWeek.Monday:
increment = 3; break;
case DayOfWeek.Tuesday:
increment = 2; break;
case DayOfWeek.Wednesday:
increment = 1; break;
case DayOfWeek.Thursday:
increment = 0; break;
case DayOfWeek.Friday:
increment = -1; break;
case DayOfWeek.Saturday:
increment = -2; break;
case DayOfWeek.Sunday:
increment = -3; break;
}
date = date.AddDays(increment);
return string.Format("{0:yyyy}-{1:00}", date, System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, System.Globalization.CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday));
case 1: // Monthly
return date.ToString("yyyy-MM");
case 2: // Yearly
return date.ToString("yyyy");
default:
throw new CheckException("Invalid Period Length value {0}", _settings.PeriodLength);
}
}
public void Cashflow(int id) {
Record = CashflowSave(getJson(id, "Cashflow Report"));
}
public object CashflowSave(JObject json) {
initialiseReport(json);
ReportField cp = new ReportField("'' AS Period", "string", "Period") { Essential = true };
_fields.Add(cp);
_fields.Add(new ReportField("0 AS BalanceBefore", "decimal", "Balance Before") { Essential = true });
_fields.Add(new ReportField("0 AS BalanceAfter", "decimal", "Balance After") { Essential = true });
addTable("Journal");
addTable("Account", "idAccount", "AccountCode", "AccountName", "AccountDescription");
addTable("!NameAddress");
addTable("Document", "idDocument", "DocumentDate", "DocumentIdentifier", "DocumentTypeId", "DocumentMemo");
fieldFor("idDocument").MakeEssential();
fieldFor("DocumentDate").MakeEssential();
addTable("DocumentType", "DocType");
fieldFor("DocumentTypeId").Hide().Essential = true;
fieldFor("idAccount").Hide().Essential = true;
_fields.Add(new ReportField("Line.VatAmount", "decimal", "VatAmount") { Hidden = true, Essential = true });
RecordFilter accountTypes = new RecordFilter("AccountType", "Account.AccountTypeId", SelectAccountTypes());
accountTypes.Set((int)AcctType.Bank, (int)AcctType.CreditCard);
DateFilter date = new DateFilter(Settings, "DocumentDate", DateRange.ThisYear);
_filters.Add(date);
_filters.Add(new RecordFilter("Account", "Journal.AccountId", SelectAccounts()));
_filters.Add(new StringFilter("AccountCode", "AccountCode"));
_filters.Add(accountTypes);
_settingsRequired = "PeriodLength,Totalling,GrandTotal,ReverseSign";
_settings.Totalling = 2;
setDefaultFields(json, "Period", "Amount");
date.Apply = false;
decimal balance = 0;
int sign = _settings.ReverseSign ? -1 : 1;
readSettings(json); // Need date filter now
if (date.Active) {
JObject b = Database.Query(@"SELECT SUM(Amount + IFNULL(DocumentType.Sign * VatAmount, 0)) AS Balance FROM Journal
LEFT JOIN Line ON idLine = idJournal
LEFT JOIN Account ON idAccount = AccountId
LEFT JOIN Document ON idDocument = DocumentId
LEFT JOIN DocumentType ON idDocumentType = DocumentTypeId
" + getFilterWhere("DocumentDate < " + Database.Quote(date.CurrentPeriod()[0]))).FirstOrDefault();
if (b != null)
balance = sign * b.AsDecimal("Balance");
}
date.Apply = true;
IEnumerable<JObject> report = from r in finishReport("Journal", "DocumentDate,,idDocument,JournalNum", @"JOIN Document ON idDocument = DocumentId
JOIN Account ON idAccount = AccountId
JOIN NameAddress ON idNameAddress = NameAddressId
JOIN DocumentType ON idDocumentType = DocumentTypeId
LEFT JOIN Line ON idLine = idJournal", json)
let amount = r.AsDecimal("Amount") + r.AsDecimal("VatAmount") * SignFor((DocType)r.AsInt("DocumentTypeId"))
select r.AddRange("Period", periodFromDate(r.AsDate("DocumentDate")),
"Amount", r.AsDecimal("Amount") + r.AsDecimal("VatAmount") * SignFor((DocType)r.AsInt("DocumentTypeId")),
"BalanceBefore", balance,
"BalanceAfter", balance += sign * amount
);
_settings.SortBy = "Period";
_sortFields = new string[] { "Period" };
return reportJson(json, report);
}
public void Names(int id) {
Record = NamesSave(getJson(id, "Names List"));
}
public object NamesSave(JObject json) {
initialiseReport(json);
namesSetup();
makeSortable("Name", "Type");
setDefaultFields(json, "Type", "Name", "Address", "PostCode", "Telephone", "Email", "Contact");
return finishReport(json, "NameAddress", "Type,Name", "");
}
void namesSetup() {
addTable("NameAddress");
fieldFor("Type").MakeEssential();
fieldFor("Type").MakeSelectable(SelectNameTypes());
_filters.Add(new SelectFilter("Type", "NameAddress.Type", SelectNameTypes()));
_filters.Add(new StringFilter("Name", "NameAddress.Name"));
_filters.Add(new StringFilter("PostCode", "NameAddress.PostCode"));
_filters.Add(new BooleanFilter("Hidden", "Hidden", false));
}
public void Members(int id) {
Record = MembersSave(getJson(id, "Members List"));
}
public object MembersSave(JObject json) {
initialiseReport(json);
membersSetup();
makeSortable("LastName", "FirstName", "MemberTypeName,LastName=MemberType");
setDefaultFields(json, "MemberTypeName", "Title", "FirstName", "LastName", "Address", "PostCode", "Telephone", "Email", "Contact", "AnnualSubscription", "PaymentAmount", "AmountDue");
return finishReport(json, "Full_Member", "LastName", "");
}
void membersSetup() {
addTable("Full_Member");
_filters.Add(new StringFilter("Name", "Full_Member.Name"));
_filters.Add(new StringFilter("PostCode", "Full_Member.PostCode"));
_filters.Add(new DecimalFilter("Amount Due", "AmountDue"));
_filters.Add(new BooleanFilter("Left", "Hidden", false));
_filters.Add(new RecordFilter("Type", "Member.MemberTypeId", SelectMemberTypes()));
}
public void Products(int id) {
Record = ProductsSave(getJson(id, "Products List"));
}
public object ProductsSave(JObject json) {
initialiseReport(json);
addTable("Product");
addTable("Account", "AccountCode", "AccountName", "AccountDescription");
addTable("AccountType");
addTable("VatCode");
_filters.Add(new StringFilter("ProductName", "Product.ProductName"));
_filters.Add(new StringFilter("ProductDescription", "Product.ProductDescription"));
_filters.Add(new DecimalFilter("UnitPrice", "Product.UnitPrice"));
makeSortable("ProductName", "UnitPrice", "Code", "AccountName", "AccountCode,AccountName=AccountCode");
setDefaultFields(json, "ProductName", "ProductDescription", "UnitPrice", "Code", "AccountName");
return finishReport(json, "Product", "ProductName", @"
LEFT JOIN Account ON idAccount = AccountId
LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId
LEFT JOIN VatCode ON idVatCode = VatCodeId
");
}
public void ProfitAndLoss(int id) {
Record = ProfitAndLossSave(getJson(id, "Profit and Loss"));
}
public object ProfitAndLossSave(JObject json) {
_settings.Totalling = 0;
_settings.GrandTotal = false;
initialiseReport(json);
addTable("!AccountType");
addTable("Account", "idAccount", "AccountCode", "AccountName", "AccountDescription");
fieldFor("idAccount").Hide();
fieldFor("AccountName")["sClass"] = "sa";
fieldFor("Heading").MakeEssential().Hide();
fieldFor("Negate").MakeEssential().Hide();
fieldFor("BalanceSheet").MakeEssential().Hide();
DateFilter date = new DateFilter(Settings, "DocumentDate", DateRange.LastYear);
ReportField cp = new ReportField("SUM(Amount) AS CurrentPeriod", "decimal", "Current Period");
_fields.Add(cp);
ReportField lp = new ReportField("SUM(Amount) AS PreviousPeriod", "decimal", "Previous Period");
_fields.Add(lp);
_filters.Add(date);
setDefaultFields(json, "AcctType", "AccountName", "CurrentPeriod", "PreviousPeriod");
_settings.SortBy = "AcctType";
_settingsRequired = "";
readSettings(json);
// P & L needs 2 period buckets for the 2 columns
DateTime[] cPeriod = date.CurrentPeriod();
cp.FullFieldName = "SUM(CASE WHEN DocumentDate >= " + Database.Quote(cPeriod[0]) + " AND DocumentDate < " + Database.Quote(cPeriod[1]) + " THEN Amount ELSE 0 END) AS CurrentPeriod";
cp["heading"] = date.PeriodName(cPeriod);
DateTime[] lPeriod = date.PreviousPeriod();
lp.FullFieldName = "SUM(CASE WHEN DocumentDate >= " + Database.Quote(lPeriod[0]) + " AND DocumentDate < " + Database.Quote(lPeriod[1]) + " THEN Amount ELSE 0 END) AS PreviousPeriod";
lp["heading"] = date.PeriodName(lPeriod);
string [] sort = new string[] { "AccountTypeId", "AccountCode", "AccountName" };
string[] fields = _fields.Where(f => f.Include || f.Essential || _sortFields.Contains(f.Name)).Select(f => f.FullFieldName).Distinct().ToArray();
JObjectEnumerable report = Database.Query("SELECT " + string.Join(",", fields)
+ @"
FROM AccountType
LEFT JOIN Account ON Account.AccountTypeId = AccountType.idAccountType
JOIN Journal ON Journal.AccountId = Account.idAccount
LEFT JOIN Document ON Document.idDocument = Journal.DocumentId
"
+ "\r\nWHERE BalanceSheet = 0"
+ "\r\nAND ((DocumentDate >= " + Database.Quote(lPeriod[0])
+ "\r\nAND DocumentDate < " + Database.Quote(cPeriod[1]) + ")"
+ "\r\nOR Account.AccountTypeId = " + (int)AcctType.Security + ")"
+ "\r\nGROUP BY idAccount"
+ "\r\nORDER BY " + string.Join(",", sort.Select(s => s + (_settings.DescendingOrder ? " DESC" : "")).ToArray())
);
// Needs further processing to add investment gains
// total, etc.
return reportJson(json, fixProfitAndLoss(addInvestmentGains(report.ToList(), "Old", lPeriod[0], "PreviousPeriod", cPeriod[0], "CurrentPeriod", cPeriod[1])), "AccountType", "Account");
}
public void Securities(int id) {
Record = SecuritiesSave(getJson(id, "Securities List"));
}
public object SecuritiesSave(JObject json) {
initialiseReport(json);
addTable("Security");
addTable("StockPrice");
_filters.Add(new StringFilter("SecurityName", "Security.SecurityName"));
_filters.Add(new StringFilter("Ticker", "Security.Ticker"));
makeSortable("SecurityName", "Ticker", "Date");
setDefaultFields(json, "SecurityName", "Ticker", "Date", "Price");
return finishReport(json, "Security", "SecurityName, Date", "JOIN StockPrice ON SecurityId = idSecurity", "Security");
}
[Auth(AccessLevel.Admin, Hide = true)]
public void Users(int id) {
Record = UsersSave(getJson(id, "Users List"));
}
public object UsersSave(JObject json) {
initialiseReport(json);
addTable("User");
addTable("Permission");
RemoveField("Password");
var levelSelect = Server.NamespaceDef.GetAccessLevel().Select();
fieldFor("AccessLevel").MakeSelectable(levelSelect);
fieldFor("FunctionAccessLevel").MakeSelectable(levelSelect);
_filters.Add(new StringFilter("Login", "User.Login"));
_filters.Add(new StringFilter("Email", "User.Email"));
_filters.Add(new RecordFilter("AccessLevel", "User.AccessLevel", levelSelect));
makeSortable("Login", "Email", "AccessLevel");
setDefaultFields(json, "Login", "Email", "AccessLevel", "ModulePermissions");
return finishReport(json, "User", "Login", "LEFT JOIN Permission ON UserId = idUser AND ModulePermissions = 1", "User");
}
public void Transactions(int id) {
Record = TransactionsSave(getJson(id, "Transactions Report"));
}
public object TransactionsSave(JObject json) {
initialiseReport(json);
addTable("Extended_Document", "idDocument", "DocumentDate", "DocumentIdentifier", "DocumentName", "DocumentAddress", "DocumentAmount", "DocumentOutstanding", "DocType", "DocumentTypeId");
fieldFor("DocumentTypeId").MakeEssential().Hide();
addTable("Journal");
addTable("Account", "AccountCode", "AccountName", "AccountDescription");
addTable("AccountType");
addTable("NameAddress");
fieldFor("Type").MakeSelectable(SelectNameTypes());
addTable("Line");
addTable("Product", "ProductName", "ProductDescription", "UnitPrice");
fieldFor("UnitPrice")["heading"] = "List Price";
addTable("VatCode");
_filters.Add(new DateFilter(Settings, "DocumentDate", DateRange.ThisMonth));
_filters.Add(new StringFilter("Id", "DocumentIdentifier"));
_filters.Add(new DecimalFilter("DocumentAmount", "Extended_Document.DocumentAmount"));
_filters.Add(new DecimalFilter("DocumentOutstanding", "Extended_Document.DocumentOutstanding"));
_filters.Add(new RecordFilter("DocumentType", "DocumentTypeId", SelectDocumentTypes()));
_filters.Add(new RecordFilter("Account", "Journal.AccountId", SelectAccounts()));
_filters.Add(new StringFilter("AccountCode", "AccountCode"));
_filters.Add(new RecordFilter("NameAddress", "Journal.NameAddressId", SelectNames()));
_filters.Add(new DecimalFilter("JournalAmount", "Journal.Amount"));
_filters.Add(new StringFilter("Memo", "Journal.Memo"));
_filters.Add(new RecordFilter("VatCode", "Line.VatCodeId", SelectVatCodes()));
_filters.Add(new RecordFilter("Product", "Line.ProductId", SelectProducts()));
makeSortable("idDocument=Trans no", "DocumentDate", "DocumentIdentifier=Doc Id", "Type,DocumentName=Document Name", "DocumentAmount", "DocType");
setDefaultFields(json, "idDocument", "DocType", "DocumentDate", "DocumentName", "DocumentIdentifier", "DocumentAmount", "DocumentOutstanding", "AccountName", "Debit", "Credit", "Qty", "Memo", "Code", "VatRate", "VatAmount");
return finishReport(json, "Journal", "idDocument,,JournalNum", @"
LEFT JOIN Line ON Line.idLine = Journal.idJournal
LEFT JOIN Extended_Document ON Extended_Document.idDocument = Journal.DocumentId
LEFT JOIN NameAddress ON NameAddress.idNameAddress = Journal.NameAddressId
LEFT JOIN VatCode ON VatCode.idVatCode = Line.VatCodeId
LEFT JOIN Account ON Account.idAccount = Journal.AccountId
LEFT JOIN AccountType ON AccountType.idAccountType = Account.AccountTypeId
LEFT JOIN Product ON Product.idProduct = Line.ProductId
", "Extended_Document", "DocumentType");
}
public void TrialBalance(int id) {
Record = TrialBalanceSave(getJson(id, "Trial Balance"));
}
public object TrialBalanceSave(JObject json) {
_settings.Totalling = 0;
_settings.GrandTotal = false;
initialiseReport(json);
addTable("!AccountType", "Heading", "AcctType");
addTable("Account", "idAccount", "AccountCode", "AccountName", "AccountDescription");
fieldFor("idAccount").Hide();
addTable("Journal", "Amount");
fieldFor("Amount").FullFieldName = "Amount";
fieldFor("Credit").FullFieldName = "Amount";
fieldFor("Debit").FullFieldName = "Amount";
DateFilter date = new DateFilter(Settings, "DocumentDate", DateRange.LastYear);
_filters.Add(date);
setDefaultFields(json, "AccountName", "Credit", "Debit");
_settings.SortBy = "AcctType";
_settingsRequired = "";
readSettings(json);
DateTime[] cPeriod = date.CurrentPeriod();
string[] sort = new string[] { "AccountTypeId", "AccountCode", "AccountName" };
string[] fields = _fields.Where(f => f.Include || f.Essential || _sortFields.Contains(f.Name)).Select(f => f.FullFieldName).Distinct().ToArray();
// Need Old (= opening balance) and final values for each account
JObjectEnumerable report = Database.Query("SELECT " + string.Join(",", fields) + @", BalanceSheet, Old
FROM AccountType
LEFT JOIN Account ON Account.AccountTypeId = AccountType.idAccountType
JOIN (SELECT AccountId,
SUM(CASE WHEN DocumentDate < " + Database.Quote(cPeriod[1]) + " AND DocumentDate >= " + Database.Quote(cPeriod[0]) + @" THEN Amount ELSE 0 END) AS Amount,
SUM(CASE WHEN DocumentDate < " + Database.Quote(cPeriod[0]) + @" THEN Amount ELSE 0 END) AS Old
FROM Journal
LEFT JOIN Document ON Document.idDocument = Journal.DocumentId
WHERE DocumentDate < " + Database.Quote(cPeriod[1]) + @"
GROUP BY AccountId
) AS Summary ON AccountId = idAccount
ORDER BY " + string.Join(",", sort.Select(s => s + (_settings.DescendingOrder ? " DESC" : "")).ToArray())
);
_sortFields = new string[] { "Heading", "AcctType", "AccountCode", "AccountName" };
// Need to add investment gains
// then process further to sort, add opening balances where required, and total
return reportJson(json, fixTrialBalance(addInvestmentGains(addRetainedEarnings(report), "Old", cPeriod[0], "Amount", cPeriod[1])), "AccountType", "Account");
}
public void VatCodes(int id) {
Record = VatCodesSave(getJson(id, "VAT Codes List"));
}
public object VatCodesSave(JObject json) {
initialiseReport(json);
vatCodeSetup();
makeSortable("Code", "VatDescription");
setDefaultFields(json, "Code", "VatDescription", "Rate");
return finishReport(json, "VatCode", "Code", "");
}
void vatCodeSetup() {
addTable("VatCode");
_filters.Add(new StringFilter("Code", "VatCode.Code"));
_filters.Add(new StringFilter("VatCodeDescription", "VatCode.VatDescription"));
_filters.Add(new DecimalFilter("Rate", "VatCode.Rate"));
}
public void VatDetail(int id) {
Record = VatDetailSave(getJson(id, "VAT Detail Report"));
}
public object VatDetailSave(JObject json) {
initialiseReport(json);
_settings.Totalling = 1;
_settings.GrandTotal = false;
addTable("Vat_Journal");
fieldFor("DocumentTypeId").MakeEssential().Hide();
fieldFor("DocumentAmount").FullFieldName = "DocumentAmount * Sign * VatType AS DocumentAmount";
fieldFor("DocumentOutstanding").FullFieldName = "DocumentOutstanding * Sign * VatType AS DocumentOutstanding";
fieldFor("VatType").MakeSelectable(SelectVatTypes());
fieldFor("LineAmount").FullFieldName = "LineAmount * Sign * VatType AS LineAmount";
fieldFor("VatAmount").FullFieldName = "VatAmount * Sign * VatType AS VatAmount";
addTable("VatCode");
_fields.Add(new ReportField("Payment.VatPaidDate", "date", "Vat Paid Date"));
positionField("VatType", 0);
positionField("Code", _fields.IndexOf(fieldFor("VatRate")));
_filters.Add(new DateFilter(Settings, "DocumentDate", DateRange.All));
_filters.Add(new VatPaidFilter("VatPaid", "Vat_Journal.VatPaid", SelectVatPayments()));
_filters.Add(new RecordFilter("DocumentType", "DocumentTypeId", SelectDocumentTypes()));
_filters.Add(new RecordFilter("VatType", "VatType", SelectVatTypes()));
makeSortable("idDocument=Trans no", "DocumentDate", "DocumentIdentifier=Doc Id", "Type,DocumentName=DocumentName", "DocumentAmount", "DocType", "Code");
setDefaultFields(json, "VatType", "DocType", "DocumentDate", "DocumentIdentifier", "DocumentName", "Memo", "Code", "VatRate", "VatAmount", "LineAmount");
return finishReport(json, "Vat_Journal", "VatType,DocumentDate", @"JOIN VatCode ON idVatCode = VatCodeId
LEFT JOIN (SELECT idDocument AS idVatPaid, DocumentDate AS VatPaidDate FROM Document) AS Payment ON Payment.idVatPaid = VatPaid", "Vat_Journal");
}
/// <summary>
/// Delete memorised report
/// </summary>
public AjaxReturn DeleteReport(int id) {
Report report = Database.Get<Report>(id);
Utils.Check(report.ReportGroup == "Memorised Reports", "Report not found");
Database.Delete(report);
return new AjaxReturn() { message = "Report deleted" };
}
/// <summary>
/// Add/update current report, with settings, to memorised reports.
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public AjaxReturn SaveReport(JObject json) {
Report report = json.To<Report>();
report.ReportGroup = "Memorised Reports";
report.ReportSettings = json.ToString();
Database.BeginTransaction();
Database.Update(report);
Database.Commit();
return new AjaxReturn() { message = "Report saved", id = report.idReport };
}
/// <summary>
/// Add a table to the report.
/// If a field list is supplied, exactly those fields are added.
/// Otherwise the id of the first table is added as an essential field, and all other non foreign key fields are added
/// If table is preceded by "!", its id is also added as an essential field
/// For Journal table, Credit & Debit are also added, as an alternative to Amount.
/// </summary>
void addTable(string table, params string[] fields) {
bool essential = _fields.FirstOrDefault(f => f.Essential) == null;
if (table.StartsWith("!")) {
table = table.Substring(1);
essential = false;
}
Table t = Database.TableFor(table);
foreach (Field f in fields.Length == 0 ? t.Fields.Where(f => (essential || f != t.PrimaryKey) && f.ForeignKey == null) : fields.Select(f => t.FieldFor(f))) {
ReportField r = new ReportField(t.Name, f);
FieldInfo fld = t.Type.GetField(f.Name);
if (fld != null) {
FieldAttribute fa = FieldAttribute.FieldFor(Database, fld, false);
if(!string.IsNullOrEmpty(fa.Heading))
r["heading"] = fa.Heading;
r["type"] = fa.Type;
}
if (essential && f == t.PrimaryKey) {
r.Essential = true;
if(Array.IndexOf(fields, f.Name) < 0)
r.Hidden = true;
essential = false;
}
_fields.Add(r);
if (table == "Journal" && f.Name == "Amount") {
ReportField rf = new ReportField(t.Name, f, "Debit") {
Name = "Debit",
FieldType = "debit"
};
_fields.Add(rf);
rf = new ReportField(t.Name, f, "Credit") {
Name = "Credit",
FieldType = "credit"
};
_fields.Add(rf);
}
}