-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirect.js
More file actions
2673 lines (2423 loc) · 102 KB
/
Copy pathdirect.js
File metadata and controls
2673 lines (2423 loc) · 102 KB
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
'use strict';
const http = require('http');
const https = require('https');
const { URL } = require('url');
const crypto = require('crypto');
const moment = require('moment');
const Table = require('cli-table');
const protocol = require('./protocol');
const { normalizeTimesheetStatus } = require('./timesheet-status');
const debug = process.env.DEBUG ? (...args) => console.error(...args) : () => {};
const APP_ID = 'TMMTIMESHEET';
const NUM_DAYS = 7;
const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
// Parent column indices (from production 204 data layout)
const PARENT_COL = {
EMPL_FULL_NAME: 0,
EMPL_ID: 1,
SCHEDULE_DESC: 2,
END_DT: 3,
S_STATUS_CD: 4,
ENABLE_SIGN_FL: 565,
// Column the browser sets to 'S' when signing (verified byte-for-byte
// against captured/sign-capture/017+018; col 667 was wrong — the server
// silently ignores it)
ACTION_CD: 23,
};
// Child column indices
const CHILD_DAY_COL = { 1: 26, 2: 27, 3: 28, 4: 29, 5: 30, 6: 31, 7: 32 };
const CHILD_COMMENT_COL = { 1: 124, 2: 135, 3: 143, 4: 144, 5: 145, 6: 146, 7: 147 };
const CHILD_LINE_DESC = 2;
const CHILD_UDT02_ID = 6; // UDT02_ID column index (verified: ZLEAVE.CMP pattern)
const CHILD_TOTAL_ENTERED = 96;
// Revision explanation column indices (K2 = TMMTS_TS_REVISION_EXP)
const REV_COL = { EXPLANATION: 0, REVISION_NO: 1, CANCELLED_CD: 4, EMPL_ID: 5, PERIOD_NO_CD: 6, TS_SCHEDULE_CD: 7, YEAR: 8, TOTAL_COLS: 9 };
// Audit column indices (K3 = TMMTS_TS_AUDIT_EXP)
const AUDIT_COL = { REVISION_NO: 0, LINE_NO: 1, DATE: 2, PROJECT: 3, ACCOUNT: 5, CHARGE_DESC: 6, DETAIL: 7 };
/**
* Thrown when a save attempt requires a revision explanation.
* The auditDetails array describes what changed.
*/
class RevisionRequiredError extends Error {
constructor(auditDetails) {
super('Revision explanation required');
this.name = 'RevisionRequiredError';
this.auditDetails = auditDetails || [];
}
}
// Java String.hashCode() — used by Costpoint framework for checkCache values
function javaHashCode(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0; // Convert to 32-bit integer
}
return hash;
}
class DirectClient {
constructor() {
this.baseUrl = '';
this.sid = '';
this.cookieJar = {}; // domain → { name → value }
this.parentData = null;
this.childData = null;
this.lastPutId = 0;
this.dates = null;
this._openAppResponse = '';
this._openRsParentResponse = '';
this.table = null;
this.timesheetStatus = 'Unknown';
this.timesheetStatusCode = '';
// Keep-alive agents for connection reuse (like a browser)
this._httpAgent = new http.Agent({ keepAlive: true });
this._httpsAgent = new https.Agent({ keepAlive: true });
}
/**
* Get the cookie jar for a specific hostname (creates if needed).
*/
_cookiesForHost(hostname) {
if (!this.cookieJar[hostname]) this.cookieJar[hostname] = {};
return this.cookieJar[hostname];
}
/**
* Build Cookie header string for a given hostname and request path.
* Only sends cookies whose path is a prefix of the request path (RFC 6265).
*/
_cookieHeader(hostname, requestPath) {
const jar = this.cookieJar[hostname];
if (!jar) return '';
const path = requestPath || '/';
return Object.entries(jar)
.filter(([, entry]) => {
// Support both old format (string value) and new format ({ value, path })
if (typeof entry === 'string') return true;
return path.startsWith(entry.path);
})
.map(([k, entry]) => k + '=' + (typeof entry === 'string' ? entry : entry.value))
.join('; ');
}
/**
* Track Set-Cookie headers from a response for the given hostname and path.
* Stores cookies with their path scope for proper path-matching on requests.
* Handles cookie deletion via Expires in the past (RFC 6265).
*/
_trackCookies(hostname, setCookieHeaders, requestPath) {
if (!setCookieHeaders) return;
const jar = this._cookiesForHost(hostname);
// Default path per RFC 6265: directory of the request URL
const defaultPath = requestPath ? requestPath.replace(/\/[^/]*$/, '') || '/' : '/';
for (const sc of setCookieHeaders) {
const match = sc.match(/^([^=]+)=([^;]*)/);
if (match) {
const name = match[1];
const value = match[2];
// Check for cookie deletion (RFC 6265: Max-Age=0 or Expires in the past).
// Max-Age takes precedence over Expires per spec — important when client
// clock is skewed relative to the server.
const maxAgeMatch = sc.match(/;\s*Max-Age=(\d+)/i);
if (maxAgeMatch) {
if (maxAgeMatch[1] === '0') {
delete jar[name];
continue;
}
// Max-Age > 0 — cookie is valid, skip Expires check
} else {
const expiresMatch = sc.match(/;\s*Expires=([^;]+)/i);
if (expiresMatch) {
const expiresDate = new Date(expiresMatch[1]);
if (expiresDate.getTime() < Date.now()) {
delete jar[name];
continue;
}
}
}
// Extract explicit Path from Set-Cookie
const pathMatch = sc.match(/;\s*Path=([^;]*)/i);
const cookiePath = pathMatch ? pathMatch[1] : defaultPath;
jar[name] = { value, path: cookiePath };
}
}
}
static async launch(url, username, password, opts) {
const client = new DirectClient();
await client._init(url, username, password, opts);
return client;
}
display() {
console.log(this.table.toString());
}
getData() {
const statusMeta = this._getTimesheetStatusMeta();
const ppWeek = this.getPayPeriodWeek();
return {
timesheetStatus: statusMeta.label,
timesheetStatusCode: statusMeta.code,
payPeriodWeek: ppWeek.week,
payPeriodWeekCount: ppWeek.of,
dates: this.dates.map(d => ({
date: d.date(),
fullDate: d.format('YYYY-MM-DD'),
dayOfWeek: d.format('ddd'),
})),
projects: this.table.map((row, idx) => ({
line: row[0],
code: row[1],
description: row[2],
payType: row[3],
hours: Object.fromEntries(
this.dates.map((d, i) => {
const v = row[i + 4];
return [d.date(), v === '' ? null : parseFloat(v)];
})
),
comments: Object.fromEntries(
this.dates.map((d, i) => {
const c = this.childData.rows[idx] ? (this.childData.rows[idx][CHILD_COMMENT_COL[i + 1]] || '') : '';
return [d.date(), c || null];
})
),
})),
};
}
/**
* Get the END_DT values for all parent rows (all available periods).
* Useful for finding the other week of a biweekly pay period.
*/
getAvailablePeriods() {
if (!this.parentData || !this.parentData.rows) return [];
return this.parentData.rows.map((row, i) => ({
index: i,
endDate: row[PARENT_COL.END_DT],
scheduleDesc: row[PARENT_COL.SCHEDULE_DESC],
}));
}
/**
* Parse "Wk N of M" from the schedule description field.
* Returns { week: N, of: M } or { week: null, of: null } if not found.
*/
getPayPeriodWeek() {
const parentRow = this.parentData && this.parentData.rows && this.parentData.rows[0];
const desc = parentRow ? parentRow[PARENT_COL.SCHEDULE_DESC] : '';
const match = desc && desc.match(/Wk\s+(\d+)\s+of\s+(\d+)/i);
if (match) {
return { week: parseInt(match[1], 10), of: parseInt(match[2], 10) };
}
return { week: null, of: null };
}
_getTimesheetStatusMeta() {
const parentRow = this.parentData && this.parentData.rows && this.parentData.rows[0];
const rawStatus = parentRow ? parentRow[PARENT_COL.S_STATUS_CD] : '';
return normalizeTimesheetStatus(rawStatus);
}
/**
* Get previous period data without mutating client state.
* Returns data in the same format as getData(), or null if unavailable.
*/
getPreviousPeriodData() {
if (!this.prevChildData || !this.parentData || this.parentData.rows.length < 2) {
return null;
}
const endDateStr = this.parentData.rows[1][PARENT_COL.END_DT];
const endDate = moment(endDateStr);
if (!endDate.isValid()) return null;
const startDate = endDate.clone().subtract(NUM_DAYS - 1, 'days');
const dates = [];
for (let i = 0; i < NUM_DAYS; i++) {
dates.push(startDate.clone().add(i, 'days'));
}
const statusCode = this.parentData.rows[1][PARENT_COL.S_STATUS_CD] || '';
const statusMeta = normalizeTimesheetStatus(statusCode);
const projects = [];
for (let i = 0; i < this.prevChildData.rows.length; i++) {
const row = this.prevChildData.rows[i];
const code = row[CHILD_UDT02_ID] || '';
const desc = row[CHILD_LINE_DESC] || '';
const payType = row[16] || '';
const hours = {};
const comments = {};
for (let d = 1; d <= NUM_DAYS; d++) {
const val = row[CHILD_DAY_COL[d]];
const comment = row[CHILD_COMMENT_COL[d]] || '';
hours[dates[d - 1].date()] = val ? parseFloat(val) : null;
comments[dates[d - 1].date()] = comment || null;
}
projects.push({
line: i,
code,
description: desc,
payType,
hours,
comments,
});
}
return {
timesheetStatus: statusMeta.label,
timesheetStatusCode: statusMeta.code,
dates: dates.map(d => ({
date: d.date(),
fullDate: d.format('YYYY-MM-DD'),
dayOfWeek: d.format('ddd'),
})),
projects,
};
}
async set(line, day, hours, comment) {
const start = this.dates[0].date();
const dayOffset = day - start;
const dayNum = dayOffset + 1;
const childCol = CHILD_DAY_COL[dayNum];
const rowNum = parseInt(this.childData.rowNums[line], 10);
// Update local child data
this.childData.rows[line][childCol] = String(hours);
// Set comment if provided
if (comment !== undefined && comment !== null) {
this.childData.rows[line][CHILD_COMMENT_COL[dayNum]] = comment;
}
// Send cell edit batch (205+208+204s+507)
const body = this._buildCellEditBatch(line, rowNum, dayNum);
const respText = await this._postServlet(body);
const parsed = protocol.parseResponse(respText);
const err = protocol.checkErrors(parsed);
if (err) throw new Error('Cell edit error: ' + err);
// Merge K1 204 response (single edited row) into local data
const k1Data = protocol.extract204(parsed, 1);
if (k1Data && k1Data.rows.length > 0) {
const respRowNum = k1Data.rowNums[0];
const idx = this.childData.rowNums.indexOf(respRowNum);
if (idx >= 0) {
this.childData.rows[idx] = k1Data.rows[0];
}
}
this._buildTableRows();
}
async setm(changes) {
for (const { line, day, hours, comment } of changes) {
await this.set(line, day, hours, comment);
}
}
async add(code, payType) {
debug('Adding project code: ' + code + (payType ? ' (payType=' + payType + ')' : ''));
// Create a new row locally at -59999 with template fields from existing rows.
// The browser copies employee defaults from existing rows before TMMTS_NEW_TS_LINE.
const numCols = this.childData.rows[0].length;
const newRow = new Array(numCols).fill('');
// Copy uniform template fields from first existing row (employee ID, pay schedule, etc.)
const TEMPLATE_COLS = [0, 150, 151, 187, 193, 194, 197, 234, 235, 336, 398];
const templateRow = this.childData.rows[0];
for (const ci of TEMPLATE_COLS) {
if (ci < templateRow.length && templateRow[ci]) newRow[ci] = templateRow[ci];
}
// col[1] and col[198] are the sequence number (next line number)
const nextSeq = String(this.childData.rows.length + 1);
newRow[1] = nextSeq;
newRow[198] = nextSeq;
// col[196] and col[393] are "N" for new rows (empty in existing rows)
newRow[196] = 'N';
newRow[393] = 'N';
this.childData.rows.push(newRow);
this.childData.rowNums.push('-59999');
if (this.childData.rowFlags) this.childData.rowFlags.push('19');
// Step 1: TMMTS_NEW_TS_LINE — register the new row with the server.
// The server populates employee defaults and establishes server-side state.
await this._newTimesheetLine();
// Step 2: Set the project code and validate it.
// Find the new row (may have been replaced by server response).
const newRowIdx = this.childData.rowNums.findIndex(n => parseInt(n, 10) < 0);
this.childData.rows[newRowIdx][CHILD_UDT02_ID] = code;
await this._validateUdt02();
// Step 3: Resolve charge via server-side lookup.
await this._resolveChargeOnServer(code, payType);
// Step 4: Post-charge validate — tells the server the charge is accepted.
// Without this, the server's session state doesn't have the Account field
// committed, causing "Account required" on save.
await this._validateUdt02();
this._buildTableRows();
}
/**
* Validate the UDT02_ID field on a new row, populating server defaults.
* Sends 205 PUT + 208 VALIDATE for UDT02_ID and updates local data.
*/
async _validateUdt02() {
const newRowIdx = this.childData.rowNums.findIndex(n => parseInt(n, 10) < 0);
const newRow = this.childData.rows[newRowIdx];
const rowNum = this.childData.rowNums[newRowIdx];
const encodedRow = protocol.encodePutRow(newRow);
const cmds = [
// 205 PUT K1
this._wrap(this._cmd(205, [
{ code: 'X', value: '0' }, { code: 'K', value: '1' },
{ code: 'C', value: rowNum }, { code: 'P', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedRow + protocol.DLM_ROW,
editFlag: '19,',
rowNumber: rowNum + ',',
}),
// 205 PUT K1 context
this._wrap(this._cmd(205, [
{ code: 'X', value: '0' },
{ name: 'rsContextOnly', value: 'Y' },
{ code: 'K', value: '1' }, { code: 'C', value: rowNum },
{ code: 'P', value: '0' }, { code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedRow + protocol.DLM_ROW,
editFlag: '19,',
rowNumber: rowNum + ',',
}),
// 208 VALIDATE UDT02_ID
this._wrap(this._cmd(208, [
{ name: 'objectId', value: 'UDT02_ID' },
{ code: 'K', value: '1' }, { code: 'C', value: rowNum },
{ code: 'P', value: '0' }, { code: 'V', value: 'true' },
])),
// 204 K0 positive + negative
...this._get204(0),
// 204 K1 positive + negative
...this._get204(1),
this._keepalive(),
];
const body = protocol.buildRequestBody(this.sid, cmds);
const respText = await this._postServlet(body);
const parsed = protocol.parseResponse(respText);
const err = protocol.checkErrors(parsed);
if (err) {
// "More than one charge found" is expected for multi-charge codes — not fatal
if (!err.includes('More than one charge')) {
throw new Error('UDT02_ID validate error: ' + err);
}
}
// Update local data with server-populated defaults
const k1Data = protocol.extract204(parsed, 1);
if (k1Data) {
const k1NewIdx = k1Data.rowNums.indexOf(rowNum);
if (k1NewIdx >= 0) {
this.childData.rows[newRowIdx] = k1Data.rows[k1NewIdx];
}
}
const k0Data = protocol.extract204(parsed, 0);
if (k0Data) this.parentData = k0Data;
}
/**
* Send CMD 300 TMMTS_NEW_TS_LINE to register a new row with the server.
* The server populates employee defaults (ID, pay schedule, etc.) and
* establishes session state needed for subsequent charge lookup.
* Mirrors: captured/add-ftb-req-233
*/
async _newTimesheetLine() {
const newRowIdx = this.childData.rowNums.findIndex(n => parseInt(n, 10) < 0);
const newRow = this.childData.rows[newRowIdx];
const rowNum = this.childData.rowNums[newRowIdx];
const parentRow = this.parentData.rows[0];
const encodedChild = protocol.encodePutRow(newRow);
const encodedParent = protocol.encodePutRow(parentRow);
const cmds = [
// 1. PUT K0 parent (editFlag=18)
this._wrap(this._cmd(205, [
{ code: 'K', value: '0' }, { code: 'C', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedParent + protocol.DLM_ROW,
editFlag: '18,',
rowNumber: '0,',
}),
// 2. PUT K1 new child (editFlag=19)
this._wrap(this._cmd(205, [
{ code: 'X', value: '0' }, { code: 'K', value: '1' },
{ code: 'C', value: rowNum }, { code: 'P', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedChild + protocol.DLM_ROW,
editFlag: '19,',
rowNumber: rowNum + ',',
}),
// 3. PUT K0 context ($rsContextOnly$=Y)
this._wrap(this._cmd(205, [
{ name: 'rsContextOnly', value: 'Y' },
{ code: 'K', value: '0' }, { code: 'C', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedParent + protocol.DLM_ROW,
editFlag: '18,',
rowNumber: '0,',
}),
// 4. PUT K1 child context ($rsContextOnly$=Y)
this._wrap(this._cmd(205, [
{ code: 'X', value: '0' },
{ name: 'rsContextOnly', value: 'Y' },
{ code: 'K', value: '1' }, { code: 'C', value: rowNum },
{ code: 'P', value: '0' }, { code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedChild + protocol.DLM_ROW,
editFlag: '19,',
rowNumber: rowNum + ',',
}),
// 5. CMD 300 TMMTS_NEW_TS_LINE
this._wrap(this._cmd(300, [
...this._actionBoilerplate(),
{ name: 'actionId', value: 'TMMTS_NEW_TS_LINE' },
{ name: 'restartFl', value: 'false' },
{ code: 'C', value: rowNum },
{ name: 'longRunActionFl', value: '0' },
{ name: 'procUniqueId', value: APP_ID + ':A:' + this.sid + ':1' },
{ name: 'psSchWorkflowNotifyFl', value: 'false' },
{ code: 'K', value: '1' },
{ code: 'P', value: '0' },
{ code: 'V', value: 'true' },
])),
// 6-7. 204 K0 positive + negative
...this._get204(0),
// 8-9. 204 K1 positive + negative
...this._get204(1),
// 10. keepalive
this._keepalive(),
];
// reqIdx=1 sets K1 as the action context (matches browser)
const body = protocol.buildRequestBody(this.sid, cmds) + '&reqIdx=1';
const respText = await this._postServlet(body);
if (respText.includes('onServletException')) {
throw new Error('TMMTS_NEW_TS_LINE caused server error. Session may be invalid.');
}
const parsed = protocol.parseResponse(respText);
const err = protocol.checkErrors(parsed);
if (err) throw new Error('TMMTS_NEW_TS_LINE error: ' + err);
// Update local data with server-populated defaults
const k1Data = protocol.extract204(parsed, 1);
if (k1Data) {
this.childData = k1Data;
}
const k0Data = protocol.extract204(parsed, 0);
if (k0Data) this.parentData = k0Data;
}
async save() {
debug('Saving timesheet...');
const body = this._buildSaveBatch();
const respText = await this._postServlet(body);
// Detect server crash response before parsing
if (respText.includes('onServletException')) {
console.error('Save response (first 500 chars):', respText.substring(0, 500));
throw new Error('Server error (session may be invalid). Please try again.');
}
const parsed = protocol.parseResponse(respText);
// Check for errors
const hasRescdError = protocol.checkRescds(parsed);
const err = protocol.checkErrors(parsed);
// Check for revision explanation required (CMD 206 returned -1).
// Check this BEFORE generic error handling — the -1 on CMD 206 is the definitive signal,
// and the server may also include an error message like "Explanation or Reject Reason is required."
if (hasRescdError && this._isSaveRevisionRequired(parsed)) {
debug('Revision explanation required — fetching audit details...');
// Refresh data from this response (server accepted the PUT, just blocked the save)
const k0Data = protocol.extract204(parsed, 0);
const k1Data = protocol.extract204(parsed, 1);
if (k0Data) this.parentData = k0Data;
if (k1Data) this.childData = k1Data;
this._buildTableRows();
const auditDetails = await this._fetchRevisionDetails();
throw new RevisionRequiredError(auditDetails);
}
if (hasRescdError || err) {
throw new Error('Save error: ' + (err || 'server rejected the save'));
}
// Refresh data from response
const k0Data = protocol.extract204(parsed, 0);
const k1Data = protocol.extract204(parsed, 1);
if (k0Data) this.parentData = k0Data;
if (k1Data) this.childData = k1Data;
this._buildTableRows();
debug('Timesheet saved.');
}
/**
* Check if the save response indicates revision explanation is required.
* This happens when CMD 206 SAVE gets result code -1.
*/
_isSaveRevisionRequired(parsed) {
const frames = protocol.parseFrames(parsed[0]);
const rescds = parsed[1];
let pos = 0;
for (let i = 0; i < frames.length; i++) {
if (pos >= rescds.length) break;
if (rescds[pos] === '-') {
if (frames[i].cmdCd === 206) return true;
pos += 2; // skip '-' and digit
} else {
pos++;
}
}
return false;
}
/**
* Fetch revision details by opening K2 (revision explanation) and K3 (audit) result sets.
* Stores revision metadata for use by saveWithExplanation().
* Returns audit detail rows for display.
*/
async _fetchRevisionDetails() {
// Step 1: Open K2 (TMMTS_TS_REVISION_EXP)
const openK2Resp = await this._postServlet(this._buildOpenRevisionRS());
protocol.parseResponse(openK2Resp); // validate response
// Step 2: Query K2 + Open K3 (TMMTS_TS_AUDIT_EXP)
const queryK2Resp = await this._postServlet(this._buildQueryRevisionAndOpenAudit());
const queryK2Parsed = protocol.parseResponse(queryK2Resp);
// Extract K2 data — find the new revision row and metadata
const k2Data = protocol.extract204(queryK2Parsed, 2);
this._revisionRowNum = '-59999';
this._revisionNumber = 1;
this._revisionMeta = null;
if (k2Data && k2Data.rows.length > 0) {
for (let i = 0; i < k2Data.rows.length; i++) {
const row = k2Data.rows[i];
const rev = parseInt(row[REV_COL.REVISION_NO], 10);
if (!isNaN(rev) && rev >= this._revisionNumber) {
this._revisionNumber = rev;
// Use this row's metadata if it has EMPL_ID
if (row[REV_COL.EMPL_ID]) {
this._revisionMeta = {
emplId: row[REV_COL.EMPL_ID],
periodNoCd: row[REV_COL.PERIOD_NO_CD] || '',
scheduleCd: row[REV_COL.TS_SCHEDULE_CD] || '',
year: row[REV_COL.YEAR] || '',
};
}
}
// Track the new row (empty explanation = the one we need to fill)
if (!row[REV_COL.EXPLANATION] && parseInt(k2Data.rowNums[i], 10) < 0) {
this._revisionRowNum = k2Data.rowNums[i];
}
}
}
// Step 3: Query K3 (audit details)
const queryK3Resp = await this._postServlet(this._buildQueryAudit());
const queryK3Parsed = protocol.parseResponse(queryK3Resp);
const k3Data = protocol.extract204(queryK3Parsed, 3);
const auditDetails = [];
if (k3Data && k3Data.rows.length > 0) {
for (const row of k3Data.rows) {
// Only include rows from the current revision
if (row[AUDIT_COL.REVISION_NO] === String(this._revisionNumber)) {
auditDetails.push({
lineNo: row[AUDIT_COL.LINE_NO] || '',
date: row[AUDIT_COL.DATE] || '',
project: row[AUDIT_COL.PROJECT] || '',
account: row[AUDIT_COL.ACCOUNT] || '',
chargeDescription: row[AUDIT_COL.CHARGE_DESC] || '',
description: row[AUDIT_COL.DETAIL] || '',
});
}
}
}
return auditDetails;
}
/**
* Save with a revision explanation after save() threw RevisionRequiredError.
* PUTs the explanation to K2 and re-saves.
*/
async saveWithExplanation(explanation) {
if (!this._revisionMeta) {
throw new Error('No revision context — call save() first.');
}
debug('Saving with revision explanation...');
const body = this._buildRevisionSaveBatch(explanation);
const respText = await this._postServlet(body);
if (respText.includes('onServletException')) {
throw new Error('Server error (session may be invalid). Please try again.');
}
const parsed = protocol.parseResponse(respText);
const hasRescdError = protocol.checkRescds(parsed);
const err = protocol.checkErrors(parsed);
if (hasRescdError || err) {
throw new Error('Save with explanation error: ' + (err || 'server rejected'));
}
// Refresh data
const k0Data = protocol.extract204(parsed, 0);
const k1Data = protocol.extract204(parsed, 1);
if (k0Data) this.parentData = k0Data;
if (k1Data) this.childData = k1Data;
this._buildTableRows();
// Clean up revision state
this._revisionNumber = null;
this._revisionMeta = null;
this._revisionRowNum = null;
debug('Timesheet saved with revision explanation.');
}
/**
* Resolve a project code via the server's charge lookup dialog.
* Performs the 3-step flow: OPEN_RS K2 → HLKP query → CMD 300 TC_TS_CHARGE_LKP_OK.
* Updates this.parentData and this.childData with the resolved charge fields.
*
* For single-charge codes (1 result), auto-selects the only option.
* For multi-charge codes, selects the row matching payType.
*/
async _resolveChargeOnServer(code, payType) {
// Step 1: PUT child row + OPEN_RS K2 for charge lookup
const openRsBody = this._buildOpenRsChargeLookup();
const openRsResp = await this._postServlet(openRsBody);
const openRsParsed = protocol.parseResponse(openRsResp);
const openRsErr = protocol.checkErrors(openRsParsed);
if (openRsErr) throw new Error('Charge lookup OPEN_RS error: ' + openRsErr);
// Step 2: HLKP query to fetch available charges
const hlkpBody = this._buildHlkpQuery(code);
const hlkpResp = await this._postServlet(hlkpBody);
const hlkpParsed = protocol.parseResponse(hlkpResp);
const hlkpErr = protocol.checkErrors(hlkpParsed);
if (hlkpErr) throw new Error('Charge lookup HLKP error: ' + hlkpErr);
// Extract K2 204 data (lookup results)
const k2Data = protocol.extract204(hlkpParsed, 2);
if (!k2Data || k2Data.rows.length === 0) {
throw new Error('No charges found for ' + code);
}
// Select the charge row
let selectedIdx;
const availablePayTypes = k2Data.rows.map(r => r[15] || '');
const hasDistinctPayTypes = availablePayTypes.some(pt => pt !== '');
debug('K2 lookup for ' + code + ': ' + k2Data.rows.length + ' rows, pay types: [' + availablePayTypes.map(p => p || '(empty)').join(', ') + ']');
if (k2Data.rows.length === 1 || !hasDistinctPayTypes) {
// Single-charge code or all rows have empty pay types — auto-select first
selectedIdx = 0;
} else if (payType) {
// Multi-charge — find the row matching the desired pay type
selectedIdx = this._findChargeRow(k2Data.rows, payType);
if (selectedIdx < 0) {
throw new Error(
'Pay type ' + payType + ' not found for ' + code + '. ' +
'Available: ' + availablePayTypes.join(', ')
);
}
} else {
throw new Error(
'Multiple charges found for ' + code + '. ' +
'Available pay types: ' + availablePayTypes.join(', ') + '. ' +
'Specify one: te add ' + code + ' <payType>'
);
}
const selectedRowNum = k2Data.rowNums[selectedIdx];
const selectedK2Row = k2Data.rows[selectedIdx];
// Copy charge fields from K2 selected row into K1 child row.
// The browser does this client-side before sending CMD 300.
const newRowIdx = this.childData.rowNums.findIndex(n => parseInt(n, 10) < 0);
const childRow = this.childData.rows[newRowIdx];
childRow[104] = selectedK2Row[5] || ''; // project code
childRow[108] = selectedK2Row[24] || ''; // combined code+payType (e.g., ZLEAVE.FTBRHB)
childRow[112] = selectedK2Row[26] || ''; // flag
childRow[376] = selectedK2Row[15] || ''; // pay type
childRow[400] = selectedK2Row[32] || ''; // project code
// Step 3: CMD 300 TC_TS_CHARGE_LKP_OK with selected charge
const lkpOkBody = this._buildChargeLkpOk(selectedK2Row, selectedRowNum);
const lkpOkResp = await this._postServlet(lkpOkBody);
if (lkpOkResp.includes('onServletException')) {
throw new Error('Charge lookup OK caused server error. Session may be invalid.');
}
const lkpOkParsed = protocol.parseResponse(lkpOkResp);
const lkpOkErr = protocol.checkErrors(lkpOkParsed);
if (lkpOkErr) throw new Error('Charge lookup OK error: ' + lkpOkErr);
// Refresh local data from response
const k0Data = protocol.extract204(lkpOkParsed, 0);
const k1Data = protocol.extract204(lkpOkParsed, 1);
if (k0Data) this.parentData = k0Data;
if (k1Data) this.childData = k1Data;
// Verify the charge was resolved (K1 should have the new row with charge data)
if (k1Data) {
const newIdx = k1Data.rowNums.indexOf('-59999');
if (newIdx < 0) {
debug('WARNING: new row -59999 not found in K1 response');
}
}
}
/**
* Sign the timesheet.
*
* Mirrors the browser's two-request flow (captured/sign-capture/017+018):
* 1. CMD 300 TMMTS_SIGN_TIMESHEET action, batched with parent PUTs that
* carry ACTION_CD='S'. This primes the server-side sign transition —
* without it the server silently ignores ACTION_CD='S' on save (the
* request round-trips cleanly but the timesheet stays unsigned).
* 2. PUT K0 + CMD 206 SAVE (what the browser sends after the user
* confirms the sign dialog) — reuses save().
*/
async sign() {
debug('Signing timesheet...');
// Step 1: fire the sign action event
const respText = await this._postServlet(this._buildSignEvent());
if (respText.includes('onServletException')) {
throw new Error('Server error during sign action. Please try again.');
}
const parsed = protocol.parseResponse(respText);
const err = protocol.checkErrors(parsed);
if (protocol.checkRescds(parsed) || err) {
throw new Error('Sign error: ' + (err || 'server rejected the sign action'));
}
// Refresh local data — the server returns the parent row with
// ACTION_CD='S' already applied
const k0Data = protocol.extract204(parsed, 0);
const k1Data = protocol.extract204(parsed, 1);
if (k0Data) this.parentData = k0Data;
if (k1Data) this.childData = k1Data;
// Step 2: confirm — browser-exact batch (capture 018): PUT K0 only with
// editFlag 18 + CMD 206. Deliberately NOT save()/_buildSaveBatch, whose
// shape diverges from the browser (editFlag 65562, all K1 rows PUT) and
// is the prime suspect for the session state that gets signs ignored.
this.parentData.rows[0][PARENT_COL.ACTION_CD] = 'S';
const confirmResp = await this._postServlet(this._buildSignConfirmBatch());
if (confirmResp.includes('onServletException')) {
throw new Error('Server error during sign confirm. Please try again.');
}
const confirmParsed = protocol.parseResponse(confirmResp);
const confirmErr = protocol.checkErrors(confirmParsed);
if (protocol.checkRescds(confirmParsed) || confirmErr) {
throw new Error('Sign confirm error: ' + (confirmErr || 'server rejected the sign save'));
}
const ck0 = protocol.extract204(confirmParsed, 0);
const ck1 = protocol.extract204(confirmParsed, 1);
if (ck0) this.parentData = ck0;
if (ck1) this.childData = ck1;
// The sign-confirm save returns no 204 data (unlike normal saves), so
// save()'s refresh is a no-op and local state still shows unsigned.
// Re-fetch explicitly so callers (and the web UI cache) see the new status.
const refreshResp = await this._postServlet(protocol.buildRequestBody(this.sid, [
...this._get204(0),
...this._get204(1),
this._keepalive(),
]));
const refreshParsed = protocol.parseResponse(refreshResp);
const freshK0 = protocol.extract204(refreshParsed, 0);
const freshK1 = protocol.extract204(refreshParsed, 1);
if (freshK0) this.parentData = freshK0;
if (freshK1) this.childData = freshK1;
this._buildTableRows();
const status = this.parentData.rows[0][PARENT_COL.S_STATUS_CD];
if (status !== 'S') {
throw new Error('Sign did not take effect (status is still "' + status + '")');
}
debug('Timesheet signed.');
}
/**
* Build the CMD 300 TMMTS_SIGN_TIMESHEET batch (browser capture 017):
* PUT K0 selected-flag (pre-sign state, editFlag 64), PUT K0 with
* ACTION_CD='S' (editFlag 82), PUT K0 context-only (editFlag 82),
* PUT K1 row 0 (editFlag 0), then the 300 action + 204 refresh + keepalive.
*/
_buildSignEvent() {
const parentRow = this.parentData.rows[0];
const parentRowNum = this.parentData.rowNums[0];
// Frame 1 sends the parent as-is; frames 2-3 send it with ACTION_CD='S'
const encodedParentPlain = protocol.encodePutRow(parentRow);
parentRow[PARENT_COL.ACTION_CD] = 'S';
const encodedParentSigned = protocol.encodePutRow(parentRow);
this._signActionSeq = (this._signActionSeq || 0) + 1;
const cmds = [
// PUT K0 selected row flag only (editFlag 64)
this._wrap(this._cmd(205, [
{ name: 'rsRowSelectedFlOnly', value: 'true' },
{ code: 'K', value: '0' }, { code: 'C', value: '0' },
{ code: 'V', value: 'true' },
]), {
data: encodedParentPlain + protocol.DLM_ROW,
editFlag: '64,',
rowNumber: parentRowNum + ',',
}),
// PUT K0 with ACTION_CD='S' (editFlag 82)
this._wrap(this._cmd(205, [
{ code: 'K', value: '0' }, { code: 'C', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedParentSigned + protocol.DLM_ROW,
editFlag: '82,',
rowNumber: parentRowNum + ',',
}),
// PUT K0 context only (editFlag 82)
this._wrap(this._cmd(205, [
{ name: 'rsContextOnly', value: 'Y' },
{ code: 'K', value: '0' }, { code: 'C', value: '0' },
{ code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: encodedParentSigned + protocol.DLM_ROW,
editFlag: '82,',
rowNumber: parentRowNum + ',',
}),
];
// PUT K1 row 0 context (editFlag 0) — skipped if there are no charge rows
if (this.childData && this.childData.rows.length > 0) {
cmds.push(this._wrap(this._cmd(205, [
{ code: 'X', value: '0' },
{ name: 'rsContextOnly', value: 'Y' },
{ code: 'K', value: '1' }, { code: 'C', value: '0' },
{ code: 'P', value: '0' }, { code: 'V', value: 'true' },
{ name: 'lastPutId', value: String(this.lastPutId++) },
]), {
data: protocol.encodePutRow(this.childData.rows[0]) + protocol.DLM_ROW,
editFlag: '0,',
rowNumber: this.childData.rowNums[0] + ',',
}));
}
cmds.push(
// CMD 300 TMMTS_SIGN_TIMESHEET (report params match the browser)
this._wrap(this._cmd(300, [
{ name: 'rptPrintAllPages', value: 'Y' },
{ name: 'rptInclCoverPage', value: 'Y' },
{ name: 'printRpt', value: 'N' },
{ name: 'rptScalingFactor', value: 'DFLT' },
{ name: 'rptPrnNofC', value: '1' },
{ name: 'downloadRpt', value: 'Y' },
{ name: 'emailRpt', value: 'N' },
{ name: 'printToFileRpt', value: 'N' },
{ name: 'rptLocale', value: 'VIEW_AS_BUILT' },
{ name: 'runAfterRptFl', value: 'Y' },
{ name: 'archiveRpt', value: 'N' },
{ name: 'rptArchRelativeAbsDt', value: 'Y' },
{ name: 'rptArchNeverDelete', value: 'Y' },
{ name: 'syncRequest', value: 'true' },
{ name: 'rptFormat', value: 'pdf' },
{ name: 'printLocalRpt', value: 'N' },
{ name: 'printSendEmail1', value: 'N' },
{ name: 'printHomePage1', value: 'N' },
{ name: 'printPopupAlert1', value: 'N' },
{ name: 'printSendEmail2', value: 'N' },
{ name: 'printHomePage2', value: 'N' },
{ name: 'printPopupAlert2', value: 'N' },
{ name: 'printSendEmail3', value: 'N' },
{ name: 'printHomePage3', value: 'N' },
{ name: 'printPopupAlert3', value: 'N' },
{ name: 'printSendEmail4', value: 'N' },
{ name: 'printHomePage4', value: 'N' },
{ name: 'printPopupAlert4', value: 'N' },
{ name: 'rptEmailAttachmentCount', value: '0' },
{ name: 'actionId', value: 'TMMTS_SIGN_TIMESHEET' },
{ name: 'restartFl', value: 'false' },
{ code: 'C', value: '0' },
{ name: 'longRunActionFl', value: '0' },
{ name: 'procUniqueId', value: APP_ID + ':A:' + this.sid + ':' + this._signActionSeq },
{ name: 'psSchWorkflowNotifyFl', value: 'false' },
{ code: 'K', value: '0' },
{ code: 'V', value: 'true' },
])),
...this._get204(0),
...this._get204(1),
this._keepalive(),