-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1730 lines (1357 loc) · 54.9 KB
/
app.js
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
//SaaS95 Copyright © 2023 by Caleb Stephens
const mysql = require('mysql2/promise');
const express = require('express')
const app = express()
const cors = require('cors');
const mustacheExpress = require('mustache-express');
const mustache = require('mustache');
const multer = require('multer');
const fs = require('fs');
const csv = require('csv-parser');
const config = require('./config.js');
const engines = require('consolidate');
const fsan = require('sanitize-filename');
const fileRateLimit = require("./resources/rateLimiter");
const validator = require('validator');
const pool = mysql.createPool({
host: config.host,
user: config.user,
password: config.password,
database: config.database,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
app.use(express.static('resources'));
app.use(cors());
app.engine('html', engines.mustache);
app.set('view engine', 'html');
app.set('views', __dirname + '/resources');
const upload = multer({ dest: "uploads/" });
app.get('/', function (req, res) {
res.send("Load App")
})
app.get('/report', function (req, res) {
res.setHeader('content-type','text/html');
app.engine('html', engines.mustache);
req.query.open_period = sanitize_date(req.query.open_period);
req.query.close_period = sanitize_date(req.query.close_period);
switch( req.query.p )
{
case 'scf': prepare_scf(req,res); break;
case 'vtb': view_tb(req,res); break;
case 'mscf': prepare_matrix_scf(req, res);break;
case 'cscf': prepare_consolidating_scf(req, res); break;
default: res.send("Report not found")
}
});
app.get('/app', function (req, res) {
res.setHeader('content-type','application/json');
app.engine('html', engines.mustache);
req.query = sanitize(req.query);
switch( req.query.p )
{
case 'dtbc': dtbc(req,res); break;
case 'ltm': ltm(req,res); break;
case 'ck_slug': ck_slug(req, res); break;
case 'gcfels': gcfels(req, res); break;
case 'get_current_reconciliation':get_current_reconciliation(req, res); break;
case 'dtbe':dtbe(req, res); break;
case 'gpp':gpp(req, res); break;
case 'purge':purge(req, res); break;
case 'sescfc':sescfc(req, res); break;
case 'dscfc':dscfc(req, res); break;
case 'snscfc':snscfc(req, res); break;
case 'gscfc':gscfc(req, res); break;
case 'scfc':scfc(req, res); break;
case 'dta':dta(req, res); break;
case 'gtm':gtm(req, res); break;
case 'stm':stm(req, res); break;
case 'sr':sr(req, res); break;
case 'dr':dr(req, res); break;
case 'gr':gr(req, res); break;
case 'get_note':get_note(req, res); break;
case 'scfn':scfn(req, res); break;
case 'gcd':gcd(req, res); break;
default: res.send('function not found')
}
})
app.get('/file', fileRateLimit, (req, res) => {
switch( req.query.p )
{
case 'ead': export_all_data(req, res);break;
default: res.send('file type not found');break;
}
})
app.post('/file', fileRateLimit, upload.single('file'), function(req, res){
switch( req.body.upload_type )
{
case 'trial_balance': save_trial_balance(req, res, fsan(req.file.filename)); break;
case 'scf_captions': save_new_cashflow_captions(req, res, fsan(req.file.filename)); break;
case 'trial_balance_coding': save_trial_balance_coding(req, res, fsan(req.file.filename));break;
case 'restore': restore_from_backup(req, res, fsan(req.file.filename));break;
default: res.send('file type not found');break;
}
});
app.get('/resource', function(req, res) {
switch( req.query.p )
{
case 'variables': get_site_variables(req, res);break;
default: res.send('resource not found');break;
}
});
app.listen(config.port, ()=>{
console.log('SaaS95 running; view at ' + config.site_url + ":" + config.port + "/main.html");
});
function sanitize(r)
{
for( i in r )
{
r[i] = validator.escape(r[i]);
}
return r;
}
function sanitize_date(d)
{
let nd = new Date(d);
let e = nd.toISOString().split("T");
return e[0];
}
function get_site_variables(req, res)
{
res.setHeader('content-type','text/javascript');
res.render('variables', {site_url: config.site_url, port: config.port});
}
async function dtbc(req,res)
{
let query = 'select * from cf_trial_balance_mapping where access_slug=?';
let accounts = [];
let ret = [];
const [results] = run_query(query, [req.query.access_slug]);
for ( i in results )
{
accounts.push({ account_caption: results[i].account_caption, account_type: results[i].account_type});
}
res.send(JSON.stringify(accounts));
}
function get_delta (account_type, starting_debit, starting_credit, ending_debit, ending_credit, return_value)
{
return_value = 0;
if(typeof starting_debit == 'undefined')
starting_debit = 0;
if(typeof starting_credit == 'undefined')
starting_credit = 0;
if(typeof ending_debit == 'undefined')
ending_debit = 0;
if(typeof ending_credit == 'undefined')
ending_credit = 0;
switch( account_type ){
case "cash":
return_value = 0;
break;
case "assets":
return_value = (ending_debit - ending_credit) - (starting_debit - starting_credit);
break;
case "contra assets":
return_value = (ending_debit - ending_credit) - (starting_debit - starting_credit);
break;
case "liabilities":
return_value = (starting_credit - starting_debit) - (ending_credit - ending_debit);
break;
case "contra liabilities":
return_value = (ending_debit - ending_credit) - (starting_debit - starting_credit);
break;
case "equity":
return_value = (starting_credit - starting_debit) - (ending_credit - ending_debit);
break;
case "contra equity":
return_value = (ending_debit - ending_credit) - (starting_debit - starting_credit);
break;
default:
return_value = 0;
}
return parseFloat(return_value).toFixed(2);
}
async function ltm(req,res)
{
ltm_func(req, res).then((tb)=>{
res.send(JSON.stringify({trial_balance: tb}));
});
}
async function ltm_func(req, res)
{
let query = 'select * from cf_trial_balance_mapping where access_slug=?';
let accounts = [];
let [results] = await run_query(query, [req.query.access_slug]);
let account_captions_by_id = {};
let account_mapping = {};
let account_id = {};
let reconciled = {};
for (k in results)
{
account_captions_by_id[results[k].id] = results[k].account_caption;
account_mapping[results[k].account_caption] = results[k].account_type;
account_id[results[k].account_caption] = results[k].id;
reconciled[ results[k].id ] = 0;
}
query = 'select * from cf_rec_table where open_period>=? and close_period<=? and access_slug=?';
[results] = await run_query(query, [req.query.stbd, req.query.etbd, req.query.access_slug]);
for( i in results )
{
reconciled[ results[i].account_id ] = parseFloat(reconciled[ results[i].account_id ]) + parseFloat(results[i].rec_value);
}
query = `select
tb.*,tbm.account_type
from
cf_trial_balance tb, cf_trial_balance_mapping tbm
where
tb.account_caption = tbm.account_caption and
tb.period_date=? and
tbm.account_type in ('assets', 'contra assets', 'liabilities','contra liabilities', 'equity', 'contra equity')
and tb.access_slug=?
or
tb.account_caption = tbm.account_caption and
tb.period_date=? and
tbm.account_type in ('assets', 'contra assets', 'liabilities','contra liabilities', 'equity', 'contra equity')
and tb.access_slug=?
order by tbm.account_type`;
let [start_date_results] = await run_query(query, [req.query.stbd, req.query.access_slug, req.query.stbd, req.query.access_slug]);
let [end_date_results] = await run_query(query, [req.query.etbd, req.query.access_slug, req.query.etbd, req.query.access_slug] );
let trial_balance_h = {};
let trial_balance_a = [];
for( i in start_date_results )
{
trial_balance_h[start_date_results[i].account_caption] = {};
}
for( i in end_date_results )
{
trial_balance_h[end_date_results[i].account_caption] = {};
}
for(i in start_date_results)
{
trial_balance_h[start_date_results[i].account_caption]['starting_debit'] = Math.abs(start_date_results[i].debit);
trial_balance_h[start_date_results[i].account_caption]['starting_credit'] = Math.abs(start_date_results[i].credit);
}
for(i in end_date_results)
{
trial_balance_h[end_date_results[i].account_caption]['ending_debit'] = Math.abs(end_date_results[i].debit);
trial_balance_h[end_date_results[i].account_caption]['ending_credit'] = Math.abs(end_date_results[i].credit);
}
//Order the object
const ordered_tb = Object.keys(trial_balance_h).sort().reduce(
(o, k)=>{
o[k]=trial_balance_h[k];
return o;
}, {}
);
for( i in ordered_tb )
{
let delta = parseFloat(get_delta( account_mapping[i], ordered_tb[i].starting_debit, ordered_tb[i].starting_credit, ordered_tb[i].ending_debit, ordered_tb[i].ending_credit )).toFixed(2);
let reconciliation_complete_number = parseFloat( delta ) + parseFloat(reconciled[ account_id[i] ] );
let reconciliation_complete;
if( Math.abs(reconciliation_complete_number) > 0 )
{
reconciliation_complete = 0;
} else {
reconciliation_complete = 1;
}
let starting = get_true_balance(account_mapping[i], ordered_tb[i].starting_debit, ordered_tb[i].starting_credit);
let ending = get_true_balance(account_mapping[i], ordered_tb[i].ending_debit, ordered_tb[i].ending_credit);
trial_balance_a.push({
account_caption: i,
account_type: account_mapping[i],
starting: starting,
ending: ending,
delta: delta,
start_date: req.query.stbd,
end_date: req.query.etbd,
id: account_id[i],
reconciliation_complete: reconciliation_complete,
reconciliation_complete_number: reconciliation_complete_number,
reconciled: parseFloat( reconciled[ account_id[i] ] ).toFixed(2)
});
}
return trial_balance_a;
}
async function get_previous_reporting_period(req)
{
let query = `select * from cf_trial_balance where period_date<? and access_slug=? order by period_date desc limit 1`;
let last_reporting_date = await run_query(query, [req.query.close_date]);
let date = last_reporting_date.period_date;
return date;
}
async function get_account_sections(req)
{
let query = `
select
sum(rt.rec_value) rec_value,
scf.section_type,
tbm.account_caption
from
statement_of_cashflows scf
inner join cf_rec_table rt on scf.id = rt.cashflow_caption_id
inner join cf_trial_balance_mapping tbm on rt.account_id = tbm.id
where
rt.open_period >= ?
and rt.close_period <= ?
and rt.access_slug=?
group by
scf.section_type, tbm.account_caption`;
let [results] = await run_query(query, [req.query.open_period, req.query.close_period, req.query.access_slug]);
let sec_acct = {};
for( i in results )
{
sec_acct[results[i].account_caption] = {};
}
for( i in results )
{
sec_acct[results[i].account_caption][results[i].section_type] = parseFloat(results[i].rec_value);
}
return sec_acct;
}
function get_true_balance(account_type, debit, credit)
{
if(typeof debit == 'undefined')
debit = 0;
if(typeof credit == 'undefined')
credit = 0;
let return_value = 0;
switch( account_type ){
case "cash":
return_value = debit - credit;
break;
case "assets":
return_value = debit - credit;
break;
case "contra assets":
return_value = debit - credit;
break;
case "liabilities":
return_value = credit - debit;
break;
case "contra liabilities":
return_value = debit - credit;
break;
case "equity":
return_value = credit - debit;
break;
case "contra equity":
return_value = debit - credit;
break;
default:
return_value = 0;
break;
}
return parseFloat(return_value).toFixed(2);
}
async function ck_slug(req, res)
{
res.send( JSON.stringify( {"status":"OK"} ));
}
async function gcfels(req,res)
{
let query = 'select * from statement_of_cashflows where access_slug=? order by section_type asc';
let [results] = await run_query(query, [req.query.access_slug]);
let cfels = [];
for( i in results)
{
cfels.push(results[i].caption_description);
}
res.send(JSON.stringify(cfels));
}
async function get_current_reconciliation(req, res)
{
let query = `
select
tb.period_date,sum(tb.debit) as debit_sum, sum(tb.credit) credit_sum
from
cf_trial_balance tb, cf_trial_balance_mapping tbm
where
tb.period_date in (?, ?)
and tbm.account_type = "cash"
and tb.account_caption = tbm.account_caption
and tb.access_slug=?
and tb.access_slug = tbm.access_slug
group by tb.period_date`;
let [results] = await run_query(query, [req.query.open_period, req.query.close_period, req.query.access_slug]);
let cash_balances = {};
for(i in results)
{
cash_balances[results[i].period_date] = results[i].debit_sum - results[i].credit_sum;
}
let change_in_cash = get_value_or_zero(cash_balances[req.query.close_period]) - get_value_or_zero(cash_balances[req.query.open_period]);
query = `select
credit - debit as cr_dr
from cf_trial_balance tb
left join
cf_trial_balance_mapping tbm
on
tbm.account_caption = tb.account_caption
where
tb.access_slug=?
and tb.period_date >= ?
and tb.period_date <= ?
and tbm.account_type in ('revenue', 'expense')
group by tb.account_caption
`;
[results] = await run_query(query, [req.query.access_slug, req.query.open_period, req.query.close_period]);
let net_income = 0;
for(i in results)
{
net_income += results[i].cr_dr;
}
query = `select sum(rec_value) as total_recs from cf_rec_table where access_slug=? and open_period=? and close_period=?`;
[results] = await run_query(query, [req.query.access_slug, req.query.open_period, req.query.close_period]);
let total_recs = get_value_or_zero(results[0].total_recs);
let total_reconciled = get_value_or_zero(net_income) + get_value_or_zero(total_recs);
res.send(JSON.stringify({total_reconciled: total_reconciled, net_income: net_income, total_recs: total_recs, change_in_cash: change_in_cash}));
}
async function dtbc(req,res)
{
let query = `select * from cf_trial_balance_mapping where access_slug=?`;
let [results] = await run_query(query, [req.query.access_slug]);
let accounts = [];
for( i in results )
{
accounts.push({account_caption: results[i].account_caption, account_type: results[i].account_type});
}
res.send(JSON.stringify(accounts));
}
async function dtbe(req,res)
{
await run_query(`delete from cf_trial_balance where period_date=? and access_slug=?`, [req.query.period, req.query.access_slug]);
res.send(JSON.stringify({status: "OK"}));
}
async function gpp(req,res)
{
res.setHeader('content-type','application/json');
let query = `select distinct DATE_FORMAT(period_date,"%Y-%m-%d") as period_date from cf_trial_balance where access_slug=? order by period_date desc`;
let [results] = await run_query(query, [req.query.access_slug]);
let re = [];
for( i in results )
{
re.push( results[i] );
}
res.send(JSON.stringify(re));
}
async function purge(req,res)
{
await run_query(`delete from cf_trial_balance where access_slug=?`, [ req.query.access_slug ]);
await run_query(`delete from cf_trial_balance_mapping where access_slug=?`, [req.query.access_slug] );
await run_query(`delete from cf_rec_table where access_slug=?`, [req.query.access_slug]);
await run_query(`delete from cf_reconciliation_notes where access_slug=?`, [req.query.access_slug]);
await run_query(`delete from statement_of_cashflows where access_slug=?`, [req.query.access_slug]);
res.send(JSON.stringify({status: "OK"}));
}
async function sescfc(req,res)
{
await run_query(`update statement_of_cashflows set caption_description=?, section_type=? where id=? and access_slug=?`, [req.query.caption_description, req.query.section_type, req.query.id, req.query.access_slug]);
res.send(JSON.stringify({status:"OK"}));
}
async function dscfc(req,res)
{
await run_query(`delete from statement_of_cashflows where id=? and access_slug=?`, [req.query.id, req.query.access_slug]);
res.send(JSON.stringify({status:"OK"}));
}
async function snscfc(req,res)
{
res.setHeader('content-type','application/json');
await run_query(`insert into statement_of_cashflows (caption_description, section_type, access_slug) values (?,?, ?)`,
[req.query.caption_description, req.query.section_type, req.query.access_slug]);
res.send(JSON.stringify({status:"OK"}));
}
async function gscfc(req,res)
{
let query = `select * from statement_of_cashflows where id=? and access_slug=?`;
const [results] = await run_query(query, [req.query.id, req.query.access_slug]);
res.send(JSON.stringify(results[0]));
}
async function scfc(req,res)
{
let query = `select cashflow_caption_id,count(*) cnt from cf_rec_table where access_slug=? group by cashflow_caption_id`;
let [results] = await run_query(query, [req.query.access_slug]);
let counts = [];
for( i in results )
{
counts[results[i].cashflow_caption_id] = results[i].cnt;
}
query = `select * from statement_of_cashflows where access_slug=?`;
[results] = await run_query(query, [req.query.access_slug]);
let captions = [];
for( i in results )
{
results[i]['used_count'] = counts[results[i].id];
captions.push( results[i] );
}
res.send(JSON.stringify(captions));
}
async function dta(req,res)
{
await run_query(`delete from cf_trial_balance_mapping where id=? and access_slug=?`, [req.query.id, req.query.access_slug]);
res.send(JSON.stringify({status:"OK"}));
}
async function gtm(req,res)
{
let query = `select * from cf_trial_balance_mapping where access_slug=?`;
let [results] = await run_query(query, [req.query.access_slug]);
let account_list = [];
for( i in results)
{
account_list.push( results[i] );
}
res.send(JSON.stringify({account_list: account_list}));
}
async function stm(req,res)
{
await run_query(`update cf_trial_balance_mapping set account_type=? where id=? and access_slug=?`,
[req.query.account_type, req.query.id, req.query.access_slug]);
res.send(JSON.stringify({status: "OK"}));
}
async function sr(req,res)
{
let recons2 = JSON.parse( Buffer.from(req.query.recons2, 'base64').toString() );
let query = `select * from statement_of_cashflows where access_slug=?`;
let [results] = await run_query(query, [req.query.access_slug]);
let captions = {};
for( i in results)
{
captions[results[i].caption_description] = results[i].id;
}
for( i in recons2)
{
await run_query(`delete from cf_rec_table where account_id=? and open_period=? and close_period=? and access_slug=?`,
[req.query.account_id, recons2[i][0].open_period, recons2[i][0].close_period, req.query.access_slug]);
}
query = `insert into cf_rec_table (cashflow_caption_id, open_period, close_period, rec_value, account_id, access_slug) values (?, ?, ?, ?, ?, ?)`;
for (i in recons2)
{
await run_query(query, [
captions[recons2[i][0].caption_description],
recons2[i][0].open_period,
recons2[i][0].close_period,
recons2[i][0].value,
req.query.account_id,
req.query.access_slug]);
}
res.send(JSON.stringify({status: "OK"}));
}
async function dr(req,res)
{
let query = `select * from cf_rec_table where id=? and access_slug=?`;
let [results] = await run_query(query,[req.query.id, req.query.access_slug]);
await run_query(`delete from cf_reconciliation_notes where cashflow_caption_id=? and open_period=? and close_period=? and account_id=? and access_slug=?`,
[results[0].cashflow_caption_id, results[0].open_period, results[0].close_period, results[0].account_id, req.query.access_slug]);
await run_query(`delete from cf_rec_table where id=? and access_slug=?`, [req.query.id, req.query.access_slug]);
res.send(JSON.stringify({'status': "OK"}));
}
async function gr(req,res)
{
let query = `select * from cf_trial_balance_mapping where id=? and access_slug=?`;
let [account] = await run_query(query, [req.query.account_id, req.query.access_slug]);
query = `select * from statement_of_cashflows where access_slug=?`;
let [results] = await run_query(query, [req.query.access_slug]);
let captions = {};
for( i in results )
{
captions[results[i].id] = results[i].caption_description;
}
query = `select *,DATE_FORMAT(open_period, "%Y-%m-%d") as open_period, DATE_FORMAT(close_period,"%Y-%m-%d") as close_period from cf_rec_table where account_id=? and open_period >= ? and close_period <= ? and access_slug=?`;
[results] = await run_query(query,[ req.query.account_id, req.query.open_period, req.query.close_period, req.query.access_slug]);
let lines = [];
for( i in results )
{
let var_name = generate_random_string(4);
lines.push({
caption: captions[results[i].cashflow_caption_id],
rec_value: results[i].rec_value,
id: results[i].id,
var_name: var_name,
open_period: results[i].open_period,
close_period: results[i].close_period
});
}
let open_balance = {debit: 0, credit: 0};
let close_balance = {debit: 0, credit: 0};
await get_balance(req.query.open_period, account[0].account_caption, req.query.access_slug).then(function(r){
open_balance.debit = get_value_or_zero(r.debit);
open_balance.credit = get_value_or_zero(r.credit);
});
await get_balance(req.query.close_period, account[0].account_caption, req.query.access_slug).then(function(r){
close_balance.debit = get_value_or_zero(r.debit);
close_balance.credit = get_value_or_zero(r.credit);
});
let open_balance_dc = get_true_balance(account[0].account_type, open_balance.debit, open_balance.credit);
let close_balance_dc = get_true_balance(account[0].account_type, close_balance.debit, close_balance.credit);
let delta = get_delta(
account[0].account_type,
get_value_or_zero(open_balance.debit),
get_value_or_zero(open_balance.credit),
get_value_or_zero(close_balance.debit),
get_value_or_zero(close_balance.credit)
);
let send = {lines: lines,
account_name: account[0].account_caption,
open_balance: open_balance_dc,
close_balance: close_balance_dc,
delta: delta};
res.send(JSON.stringify(send));
}
async function get_note(req,res)
{
let query = `select * from statement_of_cashflows where caption_description=? and access_slug=?`;
let [results] = await run_query(query, [req.query.note_caption, req.query.access_slug]);
query = `select * from cf_reconciliation_notes where account_id=? and cashflow_caption_id=? and open_period=? and close_period=? and access_slug=?`;
let [notes] = await run_query(query, [req.query.account_id, results[0].id, req.query.open_period, req.query.close_period, req.query.access_slug]);
if( notes.length === 0)
{
notes = [{note_text: ""}];
}
res.send(JSON.stringify(notes[0]));
}
async function scfn(req,res)
{
let query = `select * from statement_of_cashflows where caption_description=? and access_slug=?`;
let [results] = await run_query(query, [req.query.note_caption, req.query.access_slug]);
query = `select * from cf_reconciliation_notes where account_id=? and cashflow_caption_id=? and open_period=? and close_period=? and access_slug=?`;
let [cnt] = await run_query(query, [req.query.account_id, results[0].id, req.query.open_period, req.query.close_period, req.query.access_slug]);
if( cnt.length !== 0 )
{
query = `update cf_reconciliation_notes set note_text=? where id=? and access_slug=?`;
await run_query(query, [req.query.reconciliation_text, cnt[0].id, req.query.access_slug]);
} else {
query = `insert into cf_reconciliation_notes (account_id, cashflow_caption_id, open_period, close_period, note_text, access_slug) values (?, ?, ?, ?, ?, ?)`;
await run_query(query, [req.query.account_id, results[0].id, req.query.open_period, req.query.close_period, req.query.reconciliation_text, req.query.access_slug]);
}
res.send({status: "OK"});
}
async function gcd(req,res)
{
let query = `
select
scf.caption_description, DATE_FORMAT(rt.open_period,"%Y-%m-%d") open_period, DATE_FORMAT(rt.close_period,"%Y-%m-%d") close_period, tbm.account_caption, rt.rec_value, tbm.id as account_id
from
statement_of_cashflows scf, cf_trial_balance_mapping tbm, cf_rec_table rt
where
rt.cashflow_caption_id = ?
and rt.cashflow_caption_id = scf.id
and rt.account_id = tbm.id
and rt.access_slug= ?
and rt.open_period >= ?
and rt.close_period <= ?`;
let [results] = await run_query(query, [req.query.id, req.query.access_slug, req.query.open_period, req.query.close_period]);
let recons = [];
for( i in results )
{
recons.push(results[i]);
}
res.send(JSON.stringify(recons));
}
async function get_balance(date, account_caption, access_slug)
{
let query = `
select
distinct tb.*,tbm.account_type
from
cf_trial_balance tb, cf_trial_balance_mapping tbm
where
tb.account_caption = ?
and tb.period_date = ?
and tb.account_caption = tbm.account_caption
and tbm.account_type in ('assets', 'contra assets', 'liabilities','contra liabilities', 'equity', 'contra equity')
and tb.access_slug=?
order by tbm.account_type
`;
let [results] = await run_query(query, [ account_caption, date, access_slug ]);
if( results.length === 0 )
{
results[0] = {};;
results[0].debit = 0;
results[0].credit = 0;
}
return results[0];
}
function generate_random_string(length)
{
const characters = 'ABCDEFGHIJKLMNOP_-QRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
let i = 0;
while (i < length) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
i += 1;
}
return result;
}
function get_value_or_zero(n)
{
return n>0 ? parseFloat(n).toFixed(2) : parseFloat(0).toFixed(2);
}
async function prepare_scf(req, res)
{
get_trial_balance_deltas(req, res).then((data)=>{
res.render('statement_of_cashflows', data);
});
}
async function prepare_matrix_scf(req, res)
{
let data = await get_trial_balance_deltas(req, res);
let account_sections = await get_account_sections(req);
let rec_table = await get_scf_rec_table(req);
req.query.stbd = req.query.open_period;
req.query.etbd = req.query.close_period;
let tb = await ltm_func(req, res);
create_matrix_scf(req, res, data, tb, account_sections, rec_table);
}
async function create_matrix_scf(req, res, d, tb, as, rt)
{
app.engine('html', engines.ejs);
let matrix_rec = {};
let capar = [];
for( i in tb )
{
if( typeof as[ tb[i].account_caption ] === "undefined")
{
as[ tb[i].account_caption ] = {
"operating reconciliation": 0,
"change in operating accounts": 0,
investing: parseFloat(0),
financing: 0
};
}
if( typeof as[ tb[i].account_caption ]["operating reconciliation"] === "undefined")
as[ tb[i].account_caption ]["operating reconciliation"] = 0;
if( typeof as[ tb[i].account_caption ]["change in operating accounts"] === "undefined")
as[ tb[i].account_caption ]["change in operating accounts"] = 0;
if( typeof as[ tb[i].account_caption ]["investing"] === "undefined")
as[ tb[i].account_caption ]["investing"] = 0;
if( typeof as[ tb[i].account_caption ]["financing"] === "undefined")
as[ tb[i].account_caption ]["financing"] = 0;
let cioa = parseFloat(as[ tb[i].account_caption ]['operating reconciliation']);
let reconciling = parseFloat(as[ tb[i].account_caption ]['operating reconciliation']);
let operating = cioa + reconciling;
let investing = parseFloat(as[ tb[i].account_caption ]['investing']);
let financing = parseFloat(as[ tb[i].account_caption ]['financing']);
matrix_rec[ tb[i].account_caption ] = {
starting: tb[i].starting,
ending: tb[i].ending,
delta: tb[i].delta,
reconciling: reconciling,
cioa: cioa,
operating: operating,
investing: investing,
financing: financing
};
capar.push(tb[i].account_caption);
}
let m_obj = {open_period: d.open_period, close_period: d.close_period, net_income: d.adjusted_net_income, matrix_rec: matrix_rec, capar: capar, rt:rt, scf:d};
res.render( 'matrix_report', {open_period: d.open_period, close_period: d.close_period, net_income: d.adjusted_net_income, matrix_rec: matrix_rec, capar: capar, rt: rt, scf:d});
}
async function get_scf_rec_table(req)
{
let query = `
select
rv.*, DATE_FORMAT(rv.open_period,"%Y-%m-%d") open_period, DATE_FORMAT(rv.close_period,"%Y-%m-%d") close_period,
scf.caption_description,
tbm.account_caption
from
cf_rec_table rv,
statement_of_cashflows scf,
cf_trial_balance_mapping tbm
where
rv.access_slug=?
and rv.open_period>=?
and rv.close_period<=?
and rv.cashflow_caption_id = scf.id
and rv.account_id = tbm.id
`;
let [results] = await run_query(query, [req.query.access_slug, req.query.open_period, req.query.close_period]);
let rec_table = {};
for(i in results)
{
rec_table[results[i].caption_description] = {};
}
for(i in results)
{
rec_table[results[i].caption_description][ results[i].account_caption] = 0;
}
for( i in results )
{
rec_table[results[i].caption_description][ results[i].account_caption ] += parseFloat(results[i].rec_value);
}
return rec_table;
}
function jlog (l)