-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtaskFactsRepository.ts
More file actions
741 lines (685 loc) · 24.9 KB
/
taskFactsRepository.ts
File metadata and controls
741 lines (685 loc) · 24.9 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
import { Prisma } from '@prisma/client';
import { tmPrisma } from '../data/prisma';
import { priorityRankSql } from '../priority/priorityRankSql';
import { AnalyticsFilters } from '../types';
import { SECONDS_PER_DAY_SQL } from './constants';
import { AnalyticsQueryOptions, buildAnalyticsWhere } from './filters';
import { asOfSnapshotCondition } from './snapshotSql';
import {
AssignmentRow,
CompletedByLocationRow,
CompletedByNameRow,
CompletedByRegionRow,
CompletedProcessingHandlingTimeRow,
CompletedSummaryRow,
CompletedTimelineRow,
FilterValueRow,
FilterValueWithTextRow,
OpenTasksByNameRow,
OpenTasksByRegionLocationRow,
OverviewFilterOptionsRows,
ServiceOverviewDbRow,
SummaryTotalsRow,
TaskEventsByServiceDbRow,
TasksDuePriorityRow,
} from './types';
type OverviewFilterOptionKind =
| 'service'
| 'roleCategory'
| 'region'
| 'location'
| 'taskName'
| 'workType'
| 'assignee';
type OverviewFacetFilterKey = 'service' | 'roleCategory' | 'region' | 'location' | 'taskName' | 'workType' | 'user';
type OverviewFilterOptionRow = {
option_type: OverviewFilterOptionKind;
value: string;
text: string;
};
type OverviewFilterOptionsParams = {
filters?: AnalyticsFilters;
queryOptions?: AnalyticsQueryOptions;
includeUserFilter?: boolean;
};
type OverviewFilterOptionsInput = OverviewFilterOptionsParams | AnalyticsQueryOptions | undefined;
function buildUserOverviewCompletedFactsWhere(
snapshotId: number,
filters: AnalyticsFilters,
queryOptions?: AnalyticsQueryOptions
): Prisma.Sql {
const conditions: Prisma.Sql[] = [asOfSnapshotCondition(snapshotId)];
if (filters.completedFrom) {
conditions.push(Prisma.sql`completed_date >= ${filters.completedFrom}`);
}
if (filters.completedTo) {
conditions.push(Prisma.sql`completed_date <= ${filters.completedTo}`);
}
if (filters.user && filters.user.length > 0) {
conditions.push(Prisma.sql`assignee IN (${Prisma.join(filters.user)})`);
}
return buildAnalyticsWhere(filters, conditions, queryOptions);
}
export class TaskFactsRepository {
private resolveOverviewFilterOptionsParams(params: OverviewFilterOptionsInput): OverviewFilterOptionsParams {
if (!params) {
return {};
}
if ('filters' in params || 'queryOptions' in params || 'includeUserFilter' in params) {
return params as OverviewFilterOptionsParams;
}
return { queryOptions: params as AnalyticsQueryOptions };
}
private buildOverviewFacetWhereClause(params: {
snapshotId: number;
filters: AnalyticsFilters;
queryOptions?: AnalyticsQueryOptions;
excludeFacet: OverviewFacetFilterKey;
includeUserFilter: boolean;
}): Prisma.Sql {
const { snapshotId, filters, queryOptions, excludeFacet, includeUserFilter } = params;
const branchFilters: AnalyticsFilters = {
...filters,
};
delete branchFilters[excludeFacet];
if (!includeUserFilter) {
delete branchFilters.user;
}
const conditions: Prisma.Sql[] = [asOfSnapshotCondition(snapshotId)];
if (includeUserFilter && excludeFacet !== 'user' && filters.user && filters.user.length > 0) {
conditions.push(Prisma.sql`assignee IN (${Prisma.join(filters.user)})`);
}
return buildAnalyticsWhere(branchFilters, conditions, queryOptions);
}
async fetchServiceOverviewRows(snapshotId: number, filters: AnalyticsFilters): Promise<ServiceOverviewDbRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'due'`,
Prisma.sql`task_status = 'open'`,
]);
const priorityRank = priorityRankSql({
priorityColumn: Prisma.raw('priority'),
dateColumn: Prisma.raw('reference_date'),
});
return tmPrisma.$queryRaw<ServiceOverviewDbRow[]>(Prisma.sql`
WITH bucketed AS (
SELECT
jurisdiction_label,
assignment_state,
task_count,
${priorityRank} AS priority_rank
FROM analytics.snapshot_task_daily_facts
${whereClause}
)
SELECT
jurisdiction_label AS service,
SUM(task_count)::int AS open_tasks,
SUM(CASE WHEN assignment_state = 'Assigned' THEN task_count ELSE 0 END)::int AS assigned_tasks,
SUM(CASE WHEN priority_rank = 4 THEN task_count ELSE 0 END)::int AS urgent,
SUM(CASE WHEN priority_rank = 3 THEN task_count ELSE 0 END)::int AS high,
SUM(CASE WHEN priority_rank = 2 THEN task_count ELSE 0 END)::int AS medium,
SUM(CASE WHEN priority_rank = 1 THEN task_count ELSE 0 END)::int AS low
FROM bucketed
GROUP BY jurisdiction_label
ORDER BY service ASC
`);
}
async fetchTaskEventsByServiceRows(
snapshotId: number,
filters: AnalyticsFilters,
range: { from: Date; to: Date }
): Promise<TaskEventsByServiceDbRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`reference_date >= ${range.from}`,
Prisma.sql`reference_date <= ${range.to}`,
Prisma.sql`date_role IN ('created', 'completed', 'cancelled')`,
]);
return tmPrisma.$queryRaw<TaskEventsByServiceDbRow[]>(Prisma.sql`
SELECT
jurisdiction_label AS service,
SUM(CASE WHEN date_role = 'completed' THEN task_count ELSE 0 END)::int AS completed,
SUM(CASE WHEN date_role = 'cancelled' THEN task_count ELSE 0 END)::int AS cancelled,
SUM(CASE WHEN date_role = 'created' THEN task_count ELSE 0 END)::int AS created
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY jurisdiction_label
ORDER BY service ASC
`);
}
async fetchOverviewFilterOptionsRows(
snapshotId: number,
params?: OverviewFilterOptionsInput
): Promise<OverviewFilterOptionsRows> {
const resolved = this.resolveOverviewFilterOptionsParams(params);
const filters = resolved.filters ?? {};
const queryOptions = resolved.queryOptions;
const includeUserFilter = resolved.includeUserFilter ?? true;
const optionBranches: Prisma.Sql[] = [];
const serviceWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'service',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'service'::text AS option_type,
jurisdiction_label AS value
FROM analytics.snapshot_filter_facet_facts
${serviceWhere}
AND jurisdiction_label IS NOT NULL
GROUP BY jurisdiction_label
`);
const roleCategoryWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'roleCategory',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'roleCategory'::text AS option_type,
role_category_label AS value
FROM analytics.snapshot_filter_facet_facts
${roleCategoryWhere}
AND role_category_label IS NOT NULL
AND BTRIM(role_category_label) <> ''
GROUP BY role_category_label
`);
const regionWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'region',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'region'::text AS option_type,
region AS value
FROM analytics.snapshot_filter_facet_facts
${regionWhere}
AND region IS NOT NULL
GROUP BY region
`);
const locationWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'location',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'location'::text AS option_type,
location AS value
FROM analytics.snapshot_filter_facet_facts
${locationWhere}
AND location IS NOT NULL
GROUP BY location
`);
const taskNameWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'taskName',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'taskName'::text AS option_type,
task_name AS value
FROM analytics.snapshot_filter_facet_facts
${taskNameWhere}
AND task_name IS NOT NULL
GROUP BY task_name
`);
const workTypeWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'workType',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'workType'::text AS option_type,
work_type AS value
FROM analytics.snapshot_filter_facet_facts
${workTypeWhere}
AND work_type IS NOT NULL
GROUP BY work_type
`);
if (includeUserFilter) {
const assigneeWhere = this.buildOverviewFacetWhereClause({
snapshotId,
filters,
queryOptions,
excludeFacet: 'user',
includeUserFilter,
});
optionBranches.push(Prisma.sql`
SELECT
'assignee'::text AS option_type,
assignee AS value
FROM analytics.snapshot_filter_facet_facts
${assigneeWhere}
AND assignee IS NOT NULL
GROUP BY assignee
`);
}
const optionRows = await tmPrisma.$queryRaw<OverviewFilterOptionRow[]>(Prisma.sql`
WITH option_rows AS (
${Prisma.join(optionBranches, ' UNION ALL ')}
),
deduped_options AS (
SELECT option_type, value
FROM option_rows
GROUP BY option_type, value
)
SELECT
deduped_options.option_type,
deduped_options.value,
CASE
WHEN deduped_options.option_type = 'workType'
THEN COALESCE(work_types.label, deduped_options.value)
ELSE deduped_options.value
END AS text
FROM deduped_options
LEFT JOIN cft_task_db.work_types work_types
ON deduped_options.option_type = 'workType'
AND work_types.work_type_id = deduped_options.value
ORDER BY deduped_options.option_type ASC, text ASC, deduped_options.value ASC
`);
const services: FilterValueRow[] = [];
const roleCategories: FilterValueRow[] = [];
const regions: FilterValueRow[] = [];
const locations: FilterValueRow[] = [];
const taskNames: FilterValueRow[] = [];
const workTypes: FilterValueWithTextRow[] = [];
const assignees: FilterValueRow[] = [];
for (const row of optionRows) {
switch (row.option_type) {
case 'service':
services.push({ value: row.value });
break;
case 'roleCategory':
roleCategories.push({ value: row.value });
break;
case 'region':
regions.push({ value: row.value });
break;
case 'location':
locations.push({ value: row.value });
break;
case 'taskName':
taskNames.push({ value: row.value });
break;
case 'workType':
workTypes.push({ value: row.value, text: row.text });
break;
case 'assignee':
assignees.push({ value: row.value });
break;
default:
break;
}
}
return { services, roleCategories, regions, locations, taskNames, workTypes, assignees };
}
async fetchOpenTasksCreatedByAssignmentRows(snapshotId: number, filters: AnalyticsFilters): Promise<AssignmentRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'created'`,
Prisma.sql`task_status = 'open'`,
]);
return tmPrisma.$queryRaw<AssignmentRow[]>(Prisma.sql`
SELECT
to_char(reference_date, 'YYYY-MM-DD') AS date_key,
assignment_state,
SUM(task_count)::int AS total
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY reference_date, assignment_state
ORDER BY reference_date
`);
}
async fetchOpenTasksByNameRows(snapshotId: number, filters: AnalyticsFilters): Promise<OpenTasksByNameRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'due'`,
Prisma.sql`task_status = 'open'`,
]);
const priorityRank = priorityRankSql({
priorityColumn: Prisma.raw('priority'),
dateColumn: Prisma.raw('reference_date'),
});
return tmPrisma.$queryRaw<OpenTasksByNameRow[]>(Prisma.sql`
WITH bucketed AS (
SELECT
task_name,
task_count,
${priorityRank} AS priority_rank
FROM analytics.snapshot_task_daily_facts
${whereClause}
)
SELECT
task_name,
SUM(CASE WHEN priority_rank = 4 THEN task_count ELSE 0 END)::int AS urgent,
SUM(CASE WHEN priority_rank = 3 THEN task_count ELSE 0 END)::int AS high,
SUM(CASE WHEN priority_rank = 2 THEN task_count ELSE 0 END)::int AS medium,
SUM(CASE WHEN priority_rank = 1 THEN task_count ELSE 0 END)::int AS low
FROM bucketed
GROUP BY task_name
ORDER BY task_name ASC
`);
}
async fetchOpenTasksByRegionLocationRows(
snapshotId: number,
filters: AnalyticsFilters
): Promise<OpenTasksByRegionLocationRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'due'`,
Prisma.sql`task_status = 'open'`,
]);
const priorityRank = priorityRankSql({
priorityColumn: Prisma.raw('priority'),
dateColumn: Prisma.raw('reference_date'),
});
return tmPrisma.$queryRaw<OpenTasksByRegionLocationRow[]>(Prisma.sql`
WITH bucketed AS (
SELECT
region,
location,
task_count,
${priorityRank} AS priority_rank
FROM analytics.snapshot_task_daily_facts
${whereClause}
)
SELECT
region,
location,
SUM(task_count)::int AS open_tasks,
SUM(CASE WHEN priority_rank = 4 THEN task_count ELSE 0 END)::int AS urgent,
SUM(CASE WHEN priority_rank = 3 THEN task_count ELSE 0 END)::int AS high,
SUM(CASE WHEN priority_rank = 2 THEN task_count ELSE 0 END)::int AS medium,
SUM(CASE WHEN priority_rank = 1 THEN task_count ELSE 0 END)::int AS low
FROM bucketed
GROUP BY region, location
ORDER BY location ASC, region ASC
`);
}
async fetchOpenTasksSummaryRows(snapshotId: number, filters: AnalyticsFilters): Promise<SummaryTotalsRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'due'`,
Prisma.sql`task_status = 'open'`,
]);
const priorityRank = priorityRankSql({
priorityColumn: Prisma.raw('priority'),
dateColumn: Prisma.raw('reference_date'),
});
return tmPrisma.$queryRaw<SummaryTotalsRow[]>(Prisma.sql`
WITH bucketed AS (
SELECT
assignment_state,
task_count,
${priorityRank} AS priority_rank
FROM analytics.snapshot_task_daily_facts
${whereClause}
)
SELECT
SUM(CASE WHEN assignment_state = 'Assigned' THEN task_count ELSE 0 END)::int AS assigned,
SUM(CASE WHEN assignment_state = 'Assigned' THEN 0 ELSE task_count END)::int AS unassigned,
SUM(CASE WHEN priority_rank = 4 THEN task_count ELSE 0 END)::int AS urgent,
SUM(CASE WHEN priority_rank = 3 THEN task_count ELSE 0 END)::int AS high,
SUM(CASE WHEN priority_rank = 2 THEN task_count ELSE 0 END)::int AS medium,
SUM(CASE WHEN priority_rank = 1 THEN task_count ELSE 0 END)::int AS low
FROM bucketed
`);
}
async fetchTasksDuePriorityRows(snapshotId: number, filters: AnalyticsFilters): Promise<TasksDuePriorityRow[]> {
const whereClause = buildAnalyticsWhere(filters, [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'due'`,
Prisma.sql`task_status = 'open'`,
]);
const priorityRank = priorityRankSql({
priorityColumn: Prisma.raw('priority'),
dateColumn: Prisma.raw('reference_date'),
});
return tmPrisma.$queryRaw<TasksDuePriorityRow[]>(Prisma.sql`
WITH bucketed AS (
SELECT
reference_date,
task_count,
${priorityRank} AS priority_rank
FROM analytics.snapshot_task_daily_facts
${whereClause}
)
SELECT
to_char(reference_date, 'YYYY-MM-DD') AS date_key,
SUM(CASE WHEN priority_rank = 4 THEN task_count ELSE 0 END)::int AS urgent,
SUM(CASE WHEN priority_rank = 3 THEN task_count ELSE 0 END)::int AS high,
SUM(CASE WHEN priority_rank = 2 THEN task_count ELSE 0 END)::int AS medium,
SUM(CASE WHEN priority_rank = 1 THEN task_count ELSE 0 END)::int AS low
FROM bucketed
GROUP BY reference_date
ORDER BY reference_date
`);
}
async fetchCompletedSummaryRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date },
queryOptions?: AnalyticsQueryOptions
): Promise<CompletedSummaryRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'completed'`,
Prisma.sql`task_status = 'completed'`,
];
if (range?.from) {
conditions.push(Prisma.sql`reference_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`reference_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions, queryOptions);
return tmPrisma.$queryRaw<CompletedSummaryRow[]>(Prisma.sql`
SELECT
SUM(task_count)::int AS total,
SUM(CASE WHEN sla_flag IS TRUE THEN task_count ELSE 0 END)::int AS within
FROM analytics.snapshot_task_daily_facts
${whereClause}
`);
}
async fetchUserOverviewCompletedSummaryRows(
snapshotId: number,
filters: AnalyticsFilters,
queryOptions?: AnalyticsQueryOptions
): Promise<CompletedSummaryRow[]> {
const whereClause = buildUserOverviewCompletedFactsWhere(snapshotId, filters, queryOptions);
return tmPrisma.$queryRaw<CompletedSummaryRow[]>(Prisma.sql`
SELECT
COALESCE(SUM(tasks), 0)::int AS total,
COALESCE(SUM(within_due), 0)::int AS within
FROM analytics.snapshot_user_completed_facts
${whereClause}
`);
}
async fetchUserOverviewCompletedTaskCount(
snapshotId: number,
filters: AnalyticsFilters,
queryOptions?: AnalyticsQueryOptions
): Promise<number> {
const whereClause = buildUserOverviewCompletedFactsWhere(snapshotId, filters, queryOptions);
const rows = await tmPrisma.$queryRaw<{ total: number }[]>(Prisma.sql`
SELECT COALESCE(SUM(tasks), 0)::int AS total
FROM analytics.snapshot_user_completed_facts
${whereClause}
`);
return rows[0]?.total ?? 0;
}
async fetchCompletedTimelineRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date }
): Promise<CompletedTimelineRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'completed'`,
Prisma.sql`task_status = 'completed'`,
];
if (range?.from) {
conditions.push(Prisma.sql`reference_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`reference_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions);
return tmPrisma.$queryRaw<CompletedTimelineRow[]>(Prisma.sql`
SELECT
to_char(reference_date, 'YYYY-MM-DD') AS date_key,
SUM(task_count)::int AS total,
SUM(CASE WHEN sla_flag IS TRUE THEN task_count ELSE 0 END)::int AS within
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY reference_date
ORDER BY reference_date
`);
}
async fetchCompletedProcessingHandlingTimeRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date }
): Promise<CompletedProcessingHandlingTimeRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`LOWER(termination_reason) = 'completed'`,
Prisma.sql`completed_date IS NOT NULL`,
];
if (range?.from) {
conditions.push(Prisma.sql`completed_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`completed_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions);
return tmPrisma.$queryRaw<CompletedProcessingHandlingTimeRow[]>(Prisma.sql`
SELECT
to_char(completed_date, 'YYYY-MM-DD') AS date_key,
COUNT(*)::int AS task_count,
AVG(EXTRACT(EPOCH FROM handling_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE handling_time IS NOT NULL)::double precision AS handling_avg,
STDDEV_POP(EXTRACT(EPOCH FROM handling_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE handling_time IS NOT NULL)::double precision AS handling_stddev,
SUM(EXTRACT(EPOCH FROM handling_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE handling_time IS NOT NULL)::double precision AS handling_sum,
COUNT(handling_time)::int AS handling_count,
AVG(EXTRACT(EPOCH FROM processing_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE processing_time IS NOT NULL)::double precision AS processing_avg,
STDDEV_POP(EXTRACT(EPOCH FROM processing_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE processing_time IS NOT NULL)::double precision AS processing_stddev,
SUM(EXTRACT(EPOCH FROM processing_time) / ${SECONDS_PER_DAY_SQL}) FILTER (WHERE processing_time IS NOT NULL)::double precision AS processing_sum,
COUNT(processing_time)::int AS processing_count
FROM analytics.snapshot_task_rows
${whereClause}
GROUP BY completed_date
ORDER BY completed_date
`);
}
async fetchCompletedByNameRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date }
): Promise<CompletedByNameRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'completed'`,
Prisma.sql`task_status = 'completed'`,
];
if (range?.from) {
conditions.push(Prisma.sql`reference_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`reference_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions);
return tmPrisma.$queryRaw<CompletedByNameRow[]>(Prisma.sql`
SELECT
task_name,
SUM(task_count)::int AS total,
SUM(CASE WHEN sla_flag IS TRUE THEN task_count ELSE 0 END)::int AS within
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY task_name
ORDER BY total DESC
`);
}
async fetchCompletedByLocationRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date }
): Promise<CompletedByLocationRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'completed'`,
Prisma.sql`task_status = 'completed'`,
];
if (range?.from) {
conditions.push(Prisma.sql`reference_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`reference_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions);
return tmPrisma.$queryRaw<CompletedByLocationRow[]>(Prisma.sql`
SELECT
location,
region,
SUM(task_count)::int AS total,
SUM(CASE WHEN sla_flag IS TRUE THEN task_count ELSE 0 END)::int AS within,
SUM(handling_time_days_sum)::double precision AS handling_time_days_sum,
SUM(handling_time_days_count)::int AS handling_time_days_count,
SUM(processing_time_days_sum)::double precision AS processing_time_days_sum,
SUM(processing_time_days_count)::int AS processing_time_days_count
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY location, region
ORDER BY location ASC, region ASC
`);
}
async fetchCompletedByRegionRows(
snapshotId: number,
filters: AnalyticsFilters,
range?: { from?: Date; to?: Date }
): Promise<CompletedByRegionRow[]> {
const conditions: Prisma.Sql[] = [
asOfSnapshotCondition(snapshotId),
Prisma.sql`date_role = 'completed'`,
Prisma.sql`task_status = 'completed'`,
];
if (range?.from) {
conditions.push(Prisma.sql`reference_date >= ${range.from}`);
}
if (range?.to) {
conditions.push(Prisma.sql`reference_date <= ${range.to}`);
}
const whereClause = buildAnalyticsWhere(filters, conditions);
return tmPrisma.$queryRaw<CompletedByRegionRow[]>(Prisma.sql`
SELECT
region,
SUM(task_count)::int AS total,
SUM(CASE WHEN sla_flag IS TRUE THEN task_count ELSE 0 END)::int AS within,
SUM(handling_time_days_sum)::double precision AS handling_time_days_sum,
SUM(handling_time_days_count)::int AS handling_time_days_count,
SUM(processing_time_days_sum)::double precision AS processing_time_days_sum,
SUM(processing_time_days_count)::int AS processing_time_days_count
FROM analytics.snapshot_task_daily_facts
${whereClause}
GROUP BY region
ORDER BY region ASC
`);
}
}
export const taskFactsRepository = new TaskFactsRepository();