-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
1651 lines (1511 loc) · 69.2 KB
/
Copy pathdb.js
File metadata and controls
1651 lines (1511 loc) · 69.2 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
import mysql from "mysql2/promise";
import { EMAIL_TEMPLATE_DEFAULTS } from "./utils/emailTemplateDefaults.js";
let pool = null;
const DDL_MAX_RETRIES = 3;
const DDL_RETRY_BASE_DELAY_MS = 250;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function normalizeIdentifier(value) {
return String(value || "").trim().replace(/`/g, "");
}
function extractColumnName(columnDef) {
const match = String(columnDef || "").trim().match(/^`?([A-Za-z0-9_]+)`?/);
return match ? match[1] : "";
}
function normalizeColumnDefault(value) {
if (value == null) return null;
return String(value).trim().replace(/^['"]|['"]$/g, "");
}
function isTiDbRetryableDdlError(error) {
const message = String(error?.message || "").toLowerCase();
return (
message.includes("information schema is changed during execution") ||
message.includes("information schema changed during execution") ||
message.includes("schema is changed during execution") ||
message.includes("schema changed during execution")
);
}
async function runDdlWithRetry(poolLike, operationName, handler) {
let lastError = null;
for (let attempt = 1; attempt <= DDL_MAX_RETRIES; attempt += 1) {
try {
return await handler();
} catch (error) {
lastError = error;
if (!isTiDbRetryableDdlError(error) || attempt >= DDL_MAX_RETRIES) {
throw error;
}
const delayMs = DDL_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1);
console.warn(
`[DB DDL] Retry ${attempt}/${DDL_MAX_RETRIES} for ${operationName} after ${delayMs}ms: ${error?.message || error}`
);
await sleep(delayMs);
}
}
throw lastError;
}
async function columnExists(poolLike, tableName, columnName) {
const [rows] = await poolLike.query(
`SELECT 1
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = ?
AND column_name = ?
LIMIT 1`,
[normalizeIdentifier(tableName), normalizeIdentifier(columnName)]
);
return rows.length > 0;
}
async function getColumnMetadata(poolLike, tableName, columnName) {
const [rows] = await poolLike.query(
`SELECT
data_type,
column_type,
column_default,
is_nullable,
character_maximum_length
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = ?
AND column_name = ?
LIMIT 1`,
[normalizeIdentifier(tableName), normalizeIdentifier(columnName)]
);
return rows[0] || null;
}
async function indexExists(poolLike, tableName, indexName) {
const [rows] = await poolLike.query(
`SELECT 1
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = ?
AND index_name = ?
LIMIT 1`,
[normalizeIdentifier(tableName), normalizeIdentifier(indexName)]
);
return rows.length > 0;
}
async function ensureVarcharColumnDefinition(poolLike, tableName, columnName, length, defaultValue) {
const metadata = await getColumnMetadata(poolLike, tableName, columnName);
if (!metadata) return;
const currentLength = Number(metadata.character_maximum_length || 0);
const currentDefault = normalizeColumnDefault(metadata.column_default);
const needsAlter =
String(metadata.data_type || "").toLowerCase() !== "varchar" ||
currentLength < Number(length) ||
normalizeColumnDefault(defaultValue) !== currentDefault;
if (!needsAlter) return;
await runDdlWithRetry(
poolLike,
`modify ${tableName}.${columnName}`,
() =>
poolLike.query(
`ALTER TABLE ${normalizeIdentifier(tableName)} MODIFY COLUMN ${normalizeIdentifier(columnName)} VARCHAR(${length}) DEFAULT ?`,
[defaultValue]
)
);
}
async function ensureLargeReasonColumn(poolLike, tableName, columnName, minimumLength) {
const metadata = await getColumnMetadata(poolLike, tableName, columnName);
if (!metadata) return;
const dataType = String(metadata.data_type || "").toLowerCase();
const currentLength = Number(metadata.character_maximum_length || 0);
const alreadyWideEnough =
["text", "mediumtext", "longtext"].includes(dataType) ||
(dataType === "varchar" && currentLength >= Number(minimumLength));
if (alreadyWideEnough) return;
await runDdlWithRetry(
poolLike,
`modify ${tableName}.${columnName}`,
() =>
poolLike.query(
`ALTER TABLE ${normalizeIdentifier(tableName)} MODIFY COLUMN ${normalizeIdentifier(columnName)} VARCHAR(${minimumLength})`
)
);
}
function isProductionLike() {
return (
String(process.env.NODE_ENV || "").toLowerCase() === "production" ||
String(process.env.RENDER || "").toLowerCase() === "true" ||
Boolean(process.env.RENDER_EXTERNAL_URL)
);
}
function assertDatabaseConfig() {
if (!isProductionLike()) return;
const requiredKeys = ["DB_HOST", "DB_PORT", "DB_USER", "DB_PASSWORD", "DB_NAME"];
const missing = requiredKeys.filter((key) => !String(process.env[key] || "").trim());
if (missing.length > 0) {
throw new Error(`[DB CONFIG] Missing required environment variables: ${missing.join(", ")}`);
}
const host = String(process.env.DB_HOST || "").trim().toLowerCase();
if (host === "localhost" || host === "127.0.0.1" || host === "::1") {
throw new Error("[DB CONFIG] DB_HOST cannot point to localhost in production/Render.");
}
}
export async function getPool() {
assertDatabaseConfig();
if (pool) return pool;
const port = process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 4000;
const useSsl = process.env.DB_SSL === "true" || process.env.DB_SSL === "1";
pool = mysql.createPool({
host: process.env.DB_HOST || "localhost",
port: Number.isNaN(port) ? 4000 : port,
user: process.env.DB_USER || "root",
password: process.env.DB_PASSWORD || "",
database: process.env.DB_NAME || "test",
waitForConnections: true,
connectionLimit: 100,
queueLimit: 0,
...(useSsl && {
// TiDB Cloud uses TLS; allow non-strict verification for convenience unless user provides certs
ssl: {
rejectUnauthorized: process.env.DB_SSL_STRICT === 'true',
},
}),
});
// Quick connectivity check to surface helpful error messages early
try {
await pool.query('SELECT 1');
} catch (err) {
console.error(`Database connectivity test failed to ${process.env.DB_HOST}:${process.env.DB_PORT} (ssl=${process.env.DB_SSL}).`, err.message || err);
throw err;
}
return pool;
}
export async function closePool() {
if (!pool) return;
const current = pool;
pool = null;
try {
await current.end();
} catch (err) {
console.error("Error while closing DB pool:", err?.message || err);
}
}
export async function query(sql, params = []) {
const p = await getPool();
const [rows] = await p.execute(sql, params);
return rows;
}
const TECHNICIANS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technicians (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
phone VARCHAR(50),
upi_id VARCHAR(120),
upi_name VARCHAR(255),
service_type VARCHAR(100),
location VARCHAR(255),
status ENUM('pending','approved','rejected') DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
password_hash VARCHAR(255),
address VARCHAR(512),
region VARCHAR(255),
district VARCHAR(255),
state VARCHAR(255),
locality VARCHAR(255),
service_area_range INT DEFAULT 10,
experience INT DEFAULT 0,
specialties JSON,
pricing JSON,
settings JSON
)
`.trim();
export async function ensureTechniciansTable() {
const p = await getPool();
await p.execute(TECHNICIANS_TABLE_SQL);
}
const USERS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
full_name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255),
google_id VARCHAR(255) UNIQUE,
is_verified BOOLEAN DEFAULT FALSE,
status VARCHAR(20) DEFAULT 'approved',
settings JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`.trim();
export async function ensureUsersTable() {
const p = await getPool();
await p.execute(USERS_TABLE_SQL);
}
const OTP_REQUESTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS otp_requests (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
otp_hash VARCHAR(255) NOT NULL,
expires_at DATETIME NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_otp_email_created (email, created_at)
)
`.trim();
export async function ensureOtpRequestsTable() {
const p = await getPool();
await p.execute(OTP_REQUESTS_TABLE_SQL);
}
const OTP_RATE_LIMITS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS otp_rate_limits (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
otp_request_count INT NOT NULL DEFAULT 0,
otp_last_request_time DATETIME NULL,
otp_window_start_time DATETIME NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_otp_rate_limits_email (email)
)
`.trim();
export async function ensureOtpRateLimitsTable() {
const p = await getPool();
await p.execute(OTP_RATE_LIMITS_TABLE_SQL);
}
const SERVICE_REQUESTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS service_requests (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
technician_id INT,
service_type VARCHAR(100) NOT NULL,
vehicle_type VARCHAR(50),
vehicle_model VARCHAR(100),
address VARCHAR(512),
description TEXT,
location_lat FLOAT,
location_lng FLOAT,
drop_address VARCHAR(512),
drop_latitude DECIMAL(10, 8),
drop_longitude DECIMAL(11, 8),
route_distance_km DECIMAL(10, 2),
estimated_duration INT,
route_metadata_json JSON,
pricing_breakdown_json JSON,
estimated_price DECIMAL(10, 2),
final_price DECIMAL(10, 2),
technician_estimated_earning DECIMAL(10, 2),
vehicle_loaded_time DATETIME NULL,
drop_arrival_time DATETIME NULL,
amount DECIMAL(10, 2) DEFAULT 0.00,
applied_coupon_code VARCHAR(64),
applied_discount_percent DECIMAL(8,6) DEFAULT 0.000000,
applied_discount_amount DECIMAL(10,2) DEFAULT 0.00,
payment_status VARCHAR(50) DEFAULT 'pending',
status VARCHAR(50) DEFAULT 'pending',
contact_phone VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (technician_id) REFERENCES technicians(id)
)
`.trim();
export async function ensureServiceRequestsTable() {
const p = await getPool();
await p.execute(SERVICE_REQUESTS_TABLE_SQL);
}
const REQUEST_TIMELINE_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS request_timeline (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
request_id INT NOT NULL,
event_type VARCHAR(80) NOT NULL,
status VARCHAR(50) NULL,
title VARCHAR(255) NOT NULL,
description TEXT NULL,
actor_type VARCHAR(40) NULL,
actor_id VARCHAR(255) NULL,
metadata JSON NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_request_timeline_request_time (request_id, created_at),
FOREIGN KEY (request_id) REFERENCES service_requests(id) ON DELETE CASCADE
)
`.trim();
export async function ensureRequestTimelineTable() {
const p = await getPool();
await p.execute(REQUEST_TIMELINE_TABLE_SQL);
await addIndexIfNotExists(
p,
"request_timeline",
"idx_request_timeline_request_time",
"request_id, created_at"
);
}
const REQUEST_ATTACHMENTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS request_attachments (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
request_id INT NOT NULL,
file_name VARCHAR(255) NULL,
file_url VARCHAR(1024) NOT NULL,
mime_type VARCHAR(120) NULL,
attachment_type VARCHAR(40) NOT NULL DEFAULT 'document',
uploaded_by_type VARCHAR(40) NULL,
uploaded_by_id VARCHAR(255) NULL,
metadata JSON NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_request_attachments_request_time (request_id, created_at),
FOREIGN KEY (request_id) REFERENCES service_requests(id) ON DELETE CASCADE
)
`.trim();
export async function ensureRequestAttachmentsTable() {
const p = await getPool();
await p.execute(REQUEST_ATTACHMENTS_TABLE_SQL);
await addIndexIfNotExists(
p,
"request_attachments",
"idx_request_attachments_request_time",
"request_id, created_at"
);
}
const TECHNICIAN_SERVICES_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_services (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
service_domain VARCHAR(100) NOT NULL,
vehicle_type VARCHAR(32) NOT NULL DEFAULT '',
visit_charge DECIMAL(10, 2) NULL,
service_charge DECIMAL(10, 2) NULL,
extra_km_charge DECIMAL(10, 2) NULL,
labour_min DECIMAL(10, 2) NULL,
labour_max DECIMAL(10, 2) NULL,
delivery_charge DECIMAL(10, 2) NULL,
price_2w_min DECIMAL(10, 2) NULL,
price_2w_max DECIMAL(10, 2) NULL,
price_4w_min DECIMAL(10, 2) NULL,
price_4w_max DECIMAL(10, 2) NULL,
base_price DECIMAL(10, 2) NULL,
free_km DECIMAL(10, 2) NULL,
per_km_price DECIMAL(10, 2) NULL,
night_charge DECIMAL(10, 2) NULL,
night_type VARCHAR(16) NULL,
metadata JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uniq_technician_services (technician_id, service_domain, vehicle_type),
INDEX idx_technician_services_lookup (technician_id, service_domain),
FOREIGN KEY (technician_id) REFERENCES technicians(id)
)
`.trim();
export async function ensureTechnicianServicesTable() {
const p = await getPool();
await p.execute(TECHNICIAN_SERVICES_TABLE_SQL);
await addColumnIfNotExists(p, "technician_services", "vehicle_type VARCHAR(32) NOT NULL DEFAULT ''");
await addColumnIfNotExists(p, "technician_services", "visit_charge DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "service_charge DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "extra_km_charge DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "labour_min DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "labour_max DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "delivery_charge DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "price_2w_min DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "price_2w_max DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "price_4w_min DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "price_4w_max DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "base_price DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "free_km DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "per_km_price DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "night_charge DECIMAL(10, 2) NULL");
await addColumnIfNotExists(p, "technician_services", "night_type VARCHAR(16) NULL");
await addColumnIfNotExists(p, "technician_services", "metadata JSON");
}
const DISPATCH_OFFERS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS dispatch_offers (
id INT AUTO_INCREMENT PRIMARY KEY,
service_request_id INT NOT NULL,
technician_id INT NOT NULL,
status ENUM('pending', 'accepted', 'rejected', 'expired') DEFAULT 'pending',
sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP,
FOREIGN KEY (service_request_id) REFERENCES service_requests(id),
FOREIGN KEY (technician_id) REFERENCES technicians(id)
)
`.trim();
export async function ensureDispatchOffersTable() {
const p = await getPool();
await p.execute(DISPATCH_OFFERS_TABLE_SQL);
await addIndexIfNotExists(p, "dispatch_offers", "idx_dispatch_offers_request_status", "service_request_id, status");
await addIndexIfNotExists(p, "dispatch_offers", "idx_dispatch_offers_request_tech", "service_request_id, technician_id");
await addIndexIfNotExists(p, "dispatch_offers", "idx_dispatch_offers_tech_status", "technician_id, status");
}
const TECHNICIAN_LOCATION_HISTORY_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_location_history (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
service_request_id INT NULL,
latitude DECIMAL(10, 8) NOT NULL,
longitude DECIMAL(11, 8) NOT NULL,
captured_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_tech_location_history_tech_time (technician_id, captured_at),
INDEX idx_tech_location_history_request_time (service_request_id, captured_at)
)
`.trim();
export async function ensureTechnicianLocationHistoryTable() {
const p = await getPool();
await p.execute(TECHNICIAN_LOCATION_HISTORY_TABLE_SQL);
}
const TECHNICIAN_LOGIN_SESSIONS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_login_sessions (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
login_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
logout_at DATETIME NULL,
ended_reason VARCHAR(64) NULL,
duration_seconds INT UNSIGNED DEFAULT 0,
source VARCHAR(64) DEFAULT 'unknown',
metadata JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_tech_login_sessions_tech_login (technician_id, login_at),
INDEX idx_tech_login_sessions_tech_logout (technician_id, logout_at),
INDEX idx_tech_login_sessions_open (technician_id, logout_at, last_seen_at)
)
`.trim();
export async function ensureTechnicianLoginSessionsTable() {
const p = await getPool();
await p.execute(TECHNICIAN_LOGIN_SESSIONS_TABLE_SQL);
}
const TECHNICIAN_ACTIVITY_ALERTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_activity_alerts (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
alert_type VARCHAR(64) NOT NULL,
status VARCHAR(32) DEFAULT 'sent',
message TEXT,
metadata JSON,
sent_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_technician_activity_alerts_type_time (alert_type, sent_at),
INDEX idx_technician_activity_alerts_tech_time (technician_id, sent_at)
)
`.trim();
export async function ensureTechnicianActivityAlertsTable() {
const p = await getPool();
await p.execute(TECHNICIAN_ACTIVITY_ALERTS_TABLE_SQL);
}
const JOB_MONITORING_ALERTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS job_monitoring_alerts (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
service_request_id INT NOT NULL,
technician_id INT NULL,
reason_code VARCHAR(64) NOT NULL,
reason_text VARCHAR(255) NOT NULL,
risk_level VARCHAR(16) NOT NULL DEFAULT 'yellow',
eta_minutes DECIMAL(10, 2) NULL,
eta_arrival DATETIME NULL,
sla_deadline DATETIME NULL,
technician_lat DECIMAL(10, 8) NULL,
technician_lng DECIMAL(11, 8) NULL,
customer_lat DECIMAL(10, 8) NULL,
customer_lng DECIMAL(11, 8) NULL,
metadata JSON,
is_active BOOLEAN DEFAULT TRUE,
first_detected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_detected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
resolved_at DATETIME NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_job_monitoring_alerts_active (is_active, risk_level, last_detected_at),
INDEX idx_job_monitoring_alerts_request (service_request_id, is_active),
INDEX idx_job_monitoring_alerts_reason (reason_code, is_active)
)
`.trim();
export async function ensureJobMonitoringAlertsTable() {
const p = await getPool();
await p.execute(JOB_MONITORING_ALERTS_TABLE_SQL);
}
const NOTIFICATIONS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS notifications (
id INT AUTO_INCREMENT PRIMARY KEY,
type VARCHAR(50),
title VARCHAR(255),
message TEXT,
is_read BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`.trim();
export async function ensureNotificationsTable() {
const p = await getPool();
await p.execute(NOTIFICATIONS_TABLE_SQL);
}
const EMAIL_TEMPLATES_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS email_templates (
id INT AUTO_INCREMENT PRIMARY KEY,
event_type VARCHAR(100) NOT NULL UNIQUE,
subject VARCHAR(255) NOT NULL,
content MEDIUMTEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
`.trim();
async function seedDefaultEmailTemplates(poolLike) {
for (const template of EMAIL_TEMPLATE_DEFAULTS) {
await poolLike.execute(
`INSERT INTO email_templates (event_type, subject, content)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE event_type = event_type`,
[template.eventType, template.subject, template.content]
);
}
}
export async function ensureEmailTemplatesTable() {
const p = await getPool();
await p.execute(EMAIL_TEMPLATES_TABLE_SQL);
await addColumnIfNotExists(p, "email_templates", "subject VARCHAR(255) NOT NULL DEFAULT ''");
await addColumnIfNotExists(p, "email_templates", "content MEDIUMTEXT NOT NULL");
await addIndexIfNotExists(p, "email_templates", "idx_email_templates_event_type", "event_type");
await seedDefaultEmailTemplates(p);
}
const REVIEWS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS reviews (
id INT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
user_id INT NOT NULL,
service_request_id INT,
rating DECIMAL(2, 1) NOT NULL,
comment TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (technician_id) REFERENCES technicians(id),
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (service_request_id) REFERENCES service_requests(id)
)
`.trim();
export async function ensureReviewsTable() {
const p = await getPool();
await p.execute(REVIEWS_TABLE_SQL);
}
// Helper to add columns if they don't exist
// Using try-catch as robust way to handle "Duplicate column name" error across different MySQL versions
async function addColumnIfNotExists(pool, table, columnDef) {
const columnName = extractColumnName(columnDef);
if (!columnName) {
throw new Error(`Unable to resolve column name from definition: ${columnDef}`);
}
if (await columnExists(pool, table, columnName)) {
return;
}
try {
await runDdlWithRetry(pool, `add column ${table}.${columnName}`, () =>
pool.query(`ALTER TABLE ${normalizeIdentifier(table)} ADD COLUMN ${columnDef}`)
);
} catch (err) {
// Ignore duplicate column error (code 1060: Duplicate column name)
// Also ignore if it says something like "Duplicate field name"
if (err.code !== 'ER_DUP_FIELDNAME' && err.errno !== 1060 && !err.message?.includes("Duplicate column")) {
console.log(`Note: Could not add column ${columnDef} to ${table}, might already exist. Error: ${err.message}`);
}
}
}
async function addIndexIfNotExists(pool, table, indexName, columnsSql) {
if (await indexExists(pool, table, indexName)) {
return;
}
try {
await runDdlWithRetry(pool, `create index ${table}.${indexName}`, () =>
pool.query(
`CREATE INDEX ${normalizeIdentifier(indexName)} ON ${normalizeIdentifier(table)} (${columnsSql})`
)
);
} catch (err) {
const message = String(err?.message || "");
const isDuplicateIndex =
err.code === "ER_DUP_KEYNAME" ||
err.code === "ER_DUP_INDEX" ||
err.errno === 1061 ||
message.includes("Duplicate key name") ||
message.includes("already exists");
if (!isDuplicateIndex) {
console.log(`Note: Could not add index ${indexName} on ${table}. Error: ${message}`);
}
}
}
async function addUniqueIndexIfNotExists(pool, table, indexName, columnsSql) {
if (await indexExists(pool, table, indexName)) {
return;
}
try {
await runDdlWithRetry(pool, `create unique index ${table}.${indexName}`, () =>
pool.query(
`CREATE UNIQUE INDEX ${normalizeIdentifier(indexName)} ON ${normalizeIdentifier(table)} (${columnsSql})`
)
);
} catch (err) {
const message = String(err?.message || "");
const isDuplicateIndex =
err.code === "ER_DUP_KEYNAME" ||
err.code === "ER_DUP_INDEX" ||
err.errno === 1061 ||
message.includes("Duplicate key name") ||
message.includes("already exists");
if (!isDuplicateIndex) {
console.log(`Note: Could not add unique index ${indexName} on ${table}. Error: ${message}`);
}
}
}
export async function updateTechniciansTableSchema() {
const p = await getPool();
await addColumnIfNotExists(p, 'technicians', 'is_active BOOLEAN DEFAULT FALSE');
await addColumnIfNotExists(p, 'technicians', 'is_available BOOLEAN DEFAULT FALSE');
await addColumnIfNotExists(p, 'technicians', 'is_logged_in BOOLEAN DEFAULT FALSE');
await addColumnIfNotExists(p, 'technicians', 'latitude DECIMAL(10, 8)');
await addColumnIfNotExists(p, 'technicians', 'longitude DECIMAL(11, 8)');
await addColumnIfNotExists(p, 'technicians', 'current_lat DECIMAL(10, 8)');
await addColumnIfNotExists(p, 'technicians', 'current_lng DECIMAL(11, 8)');
await addColumnIfNotExists(p, 'technicians', 'last_location_update DATETIME NULL');
await addColumnIfNotExists(p, 'technicians', 'last_login_at DATETIME NULL');
await addColumnIfNotExists(p, 'technicians', 'last_logout_at DATETIME NULL');
await addColumnIfNotExists(p, 'technicians', 'last_seen_at DATETIME NULL');
await addColumnIfNotExists(p, 'technicians', 'login_reminder_sent_at DATETIME NULL');
await addColumnIfNotExists(p, 'technicians', 'acceptance_rate DECIMAL(5,2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'technicians', 'skill_set JSON');
await addColumnIfNotExists(p, 'technicians', 'current_job_id INT');
// New columns for comprehensive technician data model
await addColumnIfNotExists(p, 'technicians', 'resume_url VARCHAR(1024)');
await addColumnIfNotExists(p, 'technicians', 'documents JSON');
await addColumnIfNotExists(p, 'technicians', 'upi_id VARCHAR(120)');
await addColumnIfNotExists(p, 'technicians', 'upi_name VARCHAR(255)');
try {
await p.query(
`UPDATE technicians
SET upi_id = JSON_UNQUOTE(JSON_EXTRACT(payment_details, '$.upi_id'))
WHERE (upi_id IS NULL OR TRIM(upi_id) = '')
AND payment_details IS NOT NULL
AND JSON_UNQUOTE(JSON_EXTRACT(payment_details, '$.upi_id')) IS NOT NULL
AND TRIM(JSON_UNQUOTE(JSON_EXTRACT(payment_details, '$.upi_id'))) <> ''`
);
} catch (err) {
console.log("Note: could not backfill technicians.upi_id from payment_details:", err.message);
}
try {
await p.query(
`UPDATE technicians
SET upi_name = COALESCE(
NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(payment_details, '$.upi_name'))), ''),
NULLIF(TRIM(proprietor_name), ''),
NULLIF(TRIM(name), '')
)
WHERE upi_name IS NULL OR TRIM(upi_name) = ''`
);
} catch (err) {
console.log("Note: could not backfill technicians.upi_name:", err.message);
}
await addColumnIfNotExists(p, 'technicians', 'proprietor_name VARCHAR(255)');
await addColumnIfNotExists(p, 'technicians', 'alternate_phone VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'whatsapp_number VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'google_maps_link VARCHAR(1024)');
await addColumnIfNotExists(p, 'technicians', 'aadhaar_number VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'pan_number VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'business_type VARCHAR(100)');
await addColumnIfNotExists(p, 'technicians', 'gst_number VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'trade_license_number VARCHAR(50)');
await addColumnIfNotExists(p, 'technicians', 'working_hours JSON');
await addColumnIfNotExists(p, 'technicians', 'service_costs JSON');
await addColumnIfNotExists(p, 'technicians', 'payment_details JSON');
await addColumnIfNotExists(p, 'technicians', 'app_readiness JSON');
await addColumnIfNotExists(p, 'technicians', 'vehicle_types JSON');
await addColumnIfNotExists(p, 'technicians', 'settings JSON');
await addColumnIfNotExists(p, 'technicians', 'registration_payment_status VARCHAR(50) DEFAULT "pending"');
await addColumnIfNotExists(p, 'technicians', 'registration_payment_id VARCHAR(255)');
await addColumnIfNotExists(p, 'technicians', 'registration_order_id VARCHAR(255)');
// Columns already present in CREATE TABLE but added here for migration safety if table existed before
await addColumnIfNotExists(p, 'technicians', 'jobs_completed INT DEFAULT 0');
await addColumnIfNotExists(p, 'technicians', 'total_earnings DECIMAL(12, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'technicians', 'rating DECIMAL(3, 2) DEFAULT 5.00');
await addIndexIfNotExists(p, "technicians", "idx_technicians_is_logged_in", "is_logged_in");
await addIndexIfNotExists(p, "technicians", "idx_technicians_last_seen_at", "last_seen_at");
await addIndexIfNotExists(p, "technicians", "idx_technicians_login_reminder", "login_reminder_sent_at");
// New column for user phone
await addColumnIfNotExists(p, 'users', 'phone VARCHAR(50)');
}
const FILES_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS files (
id INT AUTO_INCREMENT PRIMARY KEY,
filename VARCHAR(255) UNIQUE NOT NULL,
content LONGBLOB NOT NULL,
mimetype VARCHAR(100),
size INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`.trim();
export async function ensureFilesTable() {
const p = await getPool();
await p.execute(FILES_TABLE_SQL);
}
const USER_VEHICLES_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS user_vehicles (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
type VARCHAR(50) NOT NULL,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
license_plate VARCHAR(50),
status VARCHAR(32) DEFAULT 'ready',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
`.trim();
export async function ensureUserVehiclesTable() {
const p = await getPool();
await p.execute(USER_VEHICLES_TABLE_SQL);
await addColumnIfNotExists(p, 'user_vehicles', "status VARCHAR(32) DEFAULT 'ready'");
}
const TECHNICIAN_FLEET_VEHICLES_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_fleet_vehicles (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
vehicle_type VARCHAR(64) NOT NULL,
vehicle_number VARCHAR(64) NOT NULL,
capacity VARCHAR(64) NULL,
status VARCHAR(24) NOT NULL DEFAULT 'available',
metadata JSON NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uniq_technician_fleet_vehicle_number (technician_id, vehicle_number),
INDEX idx_technician_fleet_vehicles_lookup (technician_id, status, updated_at),
FOREIGN KEY (technician_id) REFERENCES technicians(id)
)
`.trim();
export async function ensureTechnicianFleetVehiclesTable() {
const p = await getPool();
await p.execute(TECHNICIAN_FLEET_VEHICLES_TABLE_SQL);
await addColumnIfNotExists(p, "technician_fleet_vehicles", "capacity VARCHAR(64) NULL");
await addColumnIfNotExists(p, "technician_fleet_vehicles", "status VARCHAR(24) NOT NULL DEFAULT 'available'");
await addColumnIfNotExists(p, "technician_fleet_vehicles", "metadata JSON NULL");
await addColumnIfNotExists(p, "technician_fleet_vehicles", "updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
await addIndexIfNotExists(
p,
"technician_fleet_vehicles",
"idx_technician_fleet_vehicles_lookup",
"technician_id, status, updated_at"
);
}
const TECHNICIAN_TEAM_MEMBERS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS technician_team_members (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
technician_id INT NOT NULL,
name VARCHAR(255) NOT NULL,
phone VARCHAR(50) NOT NULL,
role VARCHAR(24) NOT NULL DEFAULT 'driver',
assigned_vehicle_id BIGINT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'active',
metadata JSON NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_technician_team_members_lookup (technician_id, status, updated_at),
INDEX idx_technician_team_members_vehicle (assigned_vehicle_id),
FOREIGN KEY (technician_id) REFERENCES technicians(id)
)
`.trim();
export async function ensureTechnicianTeamMembersTable() {
const p = await getPool();
await p.execute(TECHNICIAN_TEAM_MEMBERS_TABLE_SQL);
await addColumnIfNotExists(p, "technician_team_members", "assigned_vehicle_id BIGINT NULL");
await addColumnIfNotExists(p, "technician_team_members", "status VARCHAR(24) NOT NULL DEFAULT 'active'");
await addColumnIfNotExists(p, "technician_team_members", "metadata JSON NULL");
await addColumnIfNotExists(p, "technician_team_members", "updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
await addIndexIfNotExists(
p,
"technician_team_members",
"idx_technician_team_members_lookup",
"technician_id, status, updated_at"
);
await addIndexIfNotExists(
p,
"technician_team_members",
"idx_technician_team_members_vehicle",
"assigned_vehicle_id"
);
}
const DEVICE_TOKENS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS device_tokens (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
user_type ENUM('user', 'technician') NOT NULL,
token VARCHAR(512) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_user (user_id, user_type)
)
`.trim();
export async function ensureDeviceTokensTable() {
const p = await getPool();
await p.execute(DEVICE_TOKENS_TABLE_SQL);
}
const PAYMENTS_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS payments (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
service_request_id INT NOT NULL,
payment_method VARCHAR(50) DEFAULT 'razorpay',
status VARCHAR(50) DEFAULT 'pending',
currency VARCHAR(10) DEFAULT 'INR',
amount DECIMAL(10, 2),
base_amount DECIMAL(10, 2) DEFAULT 0.00,
razorpay_order_id VARCHAR(255),
razorpay_payment_id VARCHAR(255),
razorpay_signature VARCHAR(255),
platform_fee DECIMAL(10, 2) DEFAULT 0.00,
payment_fee DECIMAL(10, 2) DEFAULT 0.00,
technician_amount DECIMAL(10, 2) DEFAULT 0.00,
refunded_amount DECIMAL(10, 2) DEFAULT 0.00,
refund_status VARCHAR(20) DEFAULT 'none',
is_settled BOOLEAN DEFAULT TRUE,
payment_to_technician_status VARCHAR(20) DEFAULT 'pending',
ledger_status VARCHAR(20) DEFAULT 'pending',
wallet_transaction_id BIGINT NULL,
pricing_snapshot JSON,
verified_at DATETIME NULL,
captured_at DATETIME NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (service_request_id) REFERENCES service_requests(id)
)
`.trim();
export async function ensurePaymentsTable() {
const p = await getPool();
await p.execute(PAYMENTS_TABLE_SQL);
// Ensure columns exist if table already existed without them
await addColumnIfNotExists(p, 'payments', 'currency VARCHAR(10) DEFAULT "INR"');
await addColumnIfNotExists(p, 'payments', 'base_amount DECIMAL(10, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'payments', 'platform_fee DECIMAL(10, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'payments', 'payment_fee DECIMAL(10, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'payments', 'technician_amount DECIMAL(10, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'payments', 'refunded_amount DECIMAL(10, 2) DEFAULT 0.00');
await addColumnIfNotExists(p, 'payments', 'refund_status VARCHAR(20) DEFAULT "none"');
await addColumnIfNotExists(p, 'payments', 'is_settled BOOLEAN DEFAULT TRUE');
await addColumnIfNotExists(p, 'payments', "payment_to_technician_status VARCHAR(20) DEFAULT 'pending'");
await addColumnIfNotExists(p, 'payments', "ledger_status VARCHAR(20) DEFAULT 'pending'");
await addColumnIfNotExists(p, 'payments', 'wallet_transaction_id BIGINT NULL');
await addColumnIfNotExists(p, 'payments', 'pricing_snapshot JSON');
await addColumnIfNotExists(p, 'payments', 'verified_at DATETIME NULL');
await addColumnIfNotExists(p, 'payments', 'captured_at DATETIME NULL');
}
export async function updatePaymentsTableSchema() {
const p = await getPool();
try {
await ensureVarcharColumnDefinition(p, "payments", "status", 50, "pending");
} catch (err) {
console.log("Note: could not modify payments.status column:", err.message);
}
await addColumnIfNotExists(p, "payments", "payment_to_technician_status VARCHAR(20) DEFAULT 'pending'");
await addColumnIfNotExists(p, "payments", "currency VARCHAR(10) DEFAULT 'INR'");
await addColumnIfNotExists(p, "payments", "base_amount DECIMAL(10, 2) DEFAULT 0.00");
await addColumnIfNotExists(p, "payments", "payment_fee DECIMAL(10, 2) DEFAULT 0.00");
await addColumnIfNotExists(p, "payments", "refunded_amount DECIMAL(10, 2) DEFAULT 0.00");
await addColumnIfNotExists(p, "payments", "refund_status VARCHAR(20) DEFAULT 'none'");
await addColumnIfNotExists(p, "payments", "ledger_status VARCHAR(20) DEFAULT 'pending'");
await addColumnIfNotExists(p, "payments", "wallet_transaction_id BIGINT NULL");
await addColumnIfNotExists(p, "payments", "pricing_snapshot JSON");
await addColumnIfNotExists(p, "payments", "verified_at DATETIME NULL");
await addColumnIfNotExists(p, "payments", "captured_at DATETIME NULL");
try {
await p.query(
`UPDATE payments
SET payment_to_technician_status = 'pending'
WHERE payment_to_technician_status IS NULL OR TRIM(payment_to_technician_status) = ''`
);
} catch (err) {
console.log("Note: could not normalize payments.payment_to_technician_status:", err.message);
}
try {
await p.query(