/
tasks.ts
1383 lines (1319 loc) · 41.5 KB
/
tasks.ts
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 copy from 'copy-to-clipboard'
import {
Allow,
Allowed,
AllowedForInstance,
BackendMethod,
Entity,
EntityFilter,
Field,
FieldOptions,
FieldRef,
Fields,
IdEntity,
Relations,
SqlDatabase,
Validators,
ValueConverters,
remult,
repo,
} from 'remult'
import {
DataControl,
GridSettings,
RowButton,
} from '../common-ui-elements/interfaces'
import moment from 'moment'
import { UITools } from '../common/UITools'
import {
GeocodeResult,
GetDistanceBetween,
getCity,
getLocation,
updateGeocodeResult,
} from '../common/address-input/google-api-helpers'
import { Roles } from '../users/roles'
import { getSite, getSiteByOrg, getTitle, lev1j } from '../users/sites'
import { OrgEntity } from '../users/OrgEntity'
import {
User,
getCurrentSiteUserId,
getCurrentUserId,
matchesCurrentUserId,
} from '../users/user'
import { createId } from '@paralleldrive/cuid2'
import { TaskImage } from './TaskImage'
import { TaskStatusChanges } from './TaskStatusChanges'
import { CreatedAtField, DateField, formatDate } from './date-utils'
import { Locks } from './locks'
import {
PhoneField,
TaskContactInfo,
formatPhone,
phoneConfig,
sendWhatsappToPhone,
} from './phone'
import { taskStatus } from './taskStatus'
import { Urgency } from './urgency'
import { updateChannel } from './UpdatesChannel'
import { sendSms } from '../../server/send-sms'
import { _DisposeViewRepeaterStrategy } from '@angular/cdk/collections'
import { update } from '../../server/getGraphQL'
import {
ACTIVE_DELIVERY,
DELIVERY_DONE,
NO_PACK_READY_FOR_DELIVERY,
PACKED_READY_FOR_DELIVERY,
updateDriverOnMonday,
updateStatusOnMonday,
} from '../../server/monday-work'
import { BlockedPhone } from './blockedPhone'
import { recordChanges } from '../common/change-log/change-log'
import { updateShadagBasedOnTask } from '../../server/shadag-work'
import { updateLev1Monday } from '../../server/monday-lev1j'
const onlyDriverRules: FieldOptions<Task, string> = {
includeInApi: (t) => {
if (remult.user) {
if (t?.eventBelongToOrgUser([Roles.trainee, Roles.dispatcher]))
return true
if (
t!.createUserId === remult.user?.id &&
remult.isAllowed(Roles.trainee)
)
return true
if (t?.getSite().showContactToAnyDriver) return true
if (matchesCurrentUserId(t!.driverId, t!.org)) return true
}
if (remult.context.availableTaskIds?.includes(t?.id!)) return true
if (t?.publicVisible) return true
if (t!.isNew()) return true
return false
},
allowApiUpdate: (t) => {
if (remult.user) {
if (t?.eventBelongToOrgUser([Roles.trainee, Roles.dispatcher]))
return true
if (
t!.createUserId === remult.user?.id &&
remult.isAllowed(Roles.trainee)
)
return true
}
if (t!.isNew()) return true
return false
},
}
@Entity<Task>('tasks', {
allowApiInsert: true,
allowApiUpdate: (t) => {
if (t!.taskStatus === taskStatus.draft)
return Boolean(t?.eventBelongToOrgUser([Roles.trainee, Roles.dispatcher]))
return Boolean(t?.eventBelongToOrgUser(Roles.dispatcher))
},
allowApiRead: Allow.authenticated,
allowApiDelete: false,
saving: async (task) => {
if (!remult.user && task.isNew()) {
const user = await Task.intakeUserId()
if (!user) {
throw new Error('לא ניתן להוסיף בקשות חדשות')
}
remult.user = {
id: user,
orgs: [{ org: getSite().org, userId: user }],
showAllOrgs: false,
}
task.createUserId = user
}
if (task.isNew() && !remult.authenticated())
remult.context.availableTaskIds.push(task.id!)
if (
!remult.isAllowed(Roles.dispatcher) &&
task.isNew() &&
!task.getSite().allDeliveryRequestsAreApprovedAutomatically
)
task.taskStatus = taskStatus.draft
if (task.$.taskStatus.valueChanged()) task.statusChangeDate = new Date()
if (task.isNew() && !task.externalId)
task.externalId = (
await SqlDatabase.getDb().execute("select nextval('task_seq')")
).rows[0].nextval
if (
task.$.eventDate.valueChanged() ||
task.$.startTime.valueChanged() ||
task.$.relevantHours.valueChanged()
) {
task.validUntil = calcValidUntil(
task.eventDate,
task.startTime,
task.relevantHours
)
}
if (task.imageId?.includes('data:image/')) {
task.imageId = (await repo(TaskImage).insert({ image: task.imageId })).id
}
for (const f of [task.$.createUserId, task.$.driverId]) {
if (f.value === null) f.value = f.originalValue
}
for (const f of [task.$.addressApiResult, task.$.toAddressApiResult]) {
if (f.value && !f.value.district) await updateGeocodeResult(f.value)
task.distance = parseFloat(
GetDistanceBetween(
getLocation(task.addressApiResult),
getLocation(task.toAddressApiResult)
).toFixed(1)
)
}
await recordChanges(task, {
excludeColumns: (e) => [e.imageId, e.statusChangeDate],
})
},
saved: async (task, { isNew }) => {
if (isNew) {
await task.insertStatusChange('יצירה', task.createUserId)
if (task.taskStatus === taskStatus.draft && getSite().sendSmsOnNewDraft) {
for (const user of await repo(User).find({
where: { dispatcher: true, org: getSite().org },
})) {
await sendSms(
user.phone,
'נוספה בקשה: ' +
task.getShortDescription() +
'\n\n' +
remult.context.origin +
'/טיוטות'
)
}
}
}
if (task.getSite().syncWithMonday && task.externalId.startsWith('m:')) {
if (task.getSite() === lev1j) {
await updateLev1Monday(task)
} else {
if (task.$.taskStatus.valueChanged()) {
switch (task.taskStatus) {
case taskStatus.active:
case taskStatus.assigned:
updateStatusOnMonday(
task,
task.returnMondayStatus === NO_PACK_READY_FOR_DELIVERY
? task.returnMondayStatus
: PACKED_READY_FOR_DELIVERY
)
break
case taskStatus.driverPickedUp:
updateStatusOnMonday(task, ACTIVE_DELIVERY)
break
case taskStatus.completed:
updateStatusOnMonday(task, DELIVERY_DONE)
break
}
}
if (task.$.driverId.valueChanged()) {
if (task.driverId) {
await updateDriverOnMonday(task)
}
}
}
}
if (task.getSite().syncWithShadag && task.externalId.startsWith('s:')) {
if (task.$.driverId.valueChanged() || task.$.taskStatus.valueChanged()) {
await updateShadagBasedOnTask(task)
}
}
if (
task.getSite().sendTextMessageOnApprove &&
task.taskStatus == taskStatus.active &&
(task.$.taskStatus.valueChanged() || isNew)
) {
let phone = task.getTextMessagePhone()
if (
phone?.phone &&
(await repo(TaskStatusChanges).count({
what: SMS_CONFIRM_MESSAGE,
taskId: task.id,
})) == 0
)
await task.insertStatusChange(
SMS_CONFIRM_MESSAGE,
JSON.stringify({
phone: phone.phone,
message: await sendSms(
phone.phone,
`שלום ${phone.name},
קיבלנו את פנייתך ${task.getShortDescription()}.
ברגע שמתנדב או מתנדבת שלנו יהיו זמינים לסייע לך, הם ייצרו איתך קשר בשיחת טלפון - נא זמינותך.
במידה והסתדרת בכל דרך אחרת, נודה לעדכון בקישור הבא, בכדי שנוכל לייעל את השירות שלנו עבור פונים נוספים. לעדכון/הסרה יש להיכנס לקישור
${remult.context.origin + '/s/' + task.editLink}
שנדע ימים טובים יותר!
תודה, ${getTitle()}`
),
})
)
}
},
validation: (task) => {
if (phoneConfig.disableValidation || task.__disableValidation) return
if (
!task.addressApiResult?.results &&
!task.getSite().onlyAskForSecondAddress
)
task.$.address.error = 'כתובת לא נמצאה'
if (!task.toAddressApiResult?.results)
task.$.toAddress.error = 'כתובת לא נמצאה'
},
backendPrefilter: () => {
if (remult.context.disableOrgFiltering) return {}
let orgs = remult.user?.orgs
if (!orgs?.[0]) return getSite().tasksFilter()
return {
$or: orgs!.map(({ org }) => getSiteByOrg(org).tasksFilter()),
}
},
//@ts-ignore
apiPrefilter: () => {
if (remult.isAllowed(Roles.dispatcher)) return {}
if (remult.isAllowed(Roles.trainee))
return {
$or: [
{
taskStatus: taskStatus.draft,
createUser: remult.user!.id,
},
Task.filterActiveTasks(),
],
}
// {
// $or: [
// { draft: true, createUser: remult.user!.id },
// Task.filterActiveTasks,
// ],
// }
return Task.filterActiveTasks()
},
})
export class Task extends OrgEntity {
__disableValidation = false
sendWhatsappInvite() {
sendWhatsappToPhone(
this.driver?.phone!,
`שלום ${this.driver?.name || ''}, קיבלת נסיעה חדשה מ "${getTitle()}"
${this.getShortDescription()}
${this.getLink()}`
)
}
eventBelongToOrgUser(allowed?: Allowed) {
const user = remult.user
if (!user) return false
const userOrg = user.orgs.find(
(x) => x.org == this.org && user.id == x.userId
)
const rolesAllowed = allowed === undefined || remult.isAllowed(allowed)
return userOrg?.userId == user.id && rolesAllowed
}
isDispatcher() {
return this.eventBelongToOrgUser(Roles.dispatcher)
}
getSite() {
return getSiteByOrg(this.org)
}
getShortDescription(): string {
let message = ''
if (this.category) message = this.category + ': '
if (this.title) message += this.title + ' '
if (this.addressApiResult?.results?.length)
message += 'מ' + getCity(this.addressApiResult!)
if (this.toAddressApiResult?.results?.length)
message += ' ל' + getCity(this.toAddressApiResult)
return message + ` (${this.externalId})`
}
getMessageForDriver() {
return `שלום ${this.driver?.name || ''} ,מופיע באפליקציה שלקחת את הנסיעה:
${this.getShortDescription()} של ארגון "${getTitle()}"
והיא טרם הושלמה
נשמח אם תעדכן אותנו מה הסטטוס שלה, בקישור הבא או בהודעה חוזרת
${this.getLink()}
`
}
displayDate() {
const e = this
let result = eventDisplayDate(e)
if (e.startTime) {
let time = e.startTime
if (time.startsWith('0')) time = time.substring(1)
result += ' ' + time
}
if (this.getSite().showValidUntil) {
result += ' - ' + formatDate(e.validUntil).split(' ').reverse().join(' ')
}
return 'רלוונטי מ: ' + result
}
static filterActiveTasks(): EntityFilter<Task> {
const d = new Date()
d.setDate(d.getDate() - 1)
return {
taskStatus: { $ne: taskStatus.draft },
$or: [
{
taskStatus: taskStatus.active,
},
{
driverId: remult.user?.orgs.map((x) => x.userId),
taskStatus: [taskStatus.assigned, taskStatus.driverPickedUp],
},
{
driverId: remult.user?.orgs.map((x) => x.userId),
statusChangeDate: { $gte: d },
},
],
}
}
@Fields.string<Task>({
caption: 'מה משנעים *',
validate: (s, c) => {
if (s.__disableValidation) return
Validators.required(s, c)
},
})
title = ''
@DataControl({ width: '120' })
@Field(() => taskStatus, { allowApiUpdate: false })
taskStatus: taskStatus = taskStatus.active
@DataControl({ width: '120' })
@DateField({
allowApiUpdate: false,
caption: 'סטטוס עדכון אחרון',
displayValue: (_, d) => formatDate(d),
})
statusChangeDate = new Date()
@Fields.string({
caption: 'פרטים נוספים',
customInput: (x) => x.textarea(),
})
description = ''
@DataControl<Task>({ visible: (t) => t.getSite().canSeeUrgency() })
@Field(() => Urgency)
urgency = Urgency.normal
@DataControl({
valueList: () => getSite().categories.map((x) => ({ id: x, caption: x })),
})
@Fields.string({ caption: 'קטגוריה' })
category: string = getSite().defaultCategory
@Fields.dateOnly<Task>({
caption: 'תאריך הסיוע המבוקש',
displayValue: (e, v) => eventDisplayDate(e),
validate: (s, c) => {
if (s.__disableValidation) return
if (!c.value || c.value.getFullYear() < 2018) c.error = 'תאריך שגוי'
var twoDaysAgo = new Date()
twoDaysAgo.setDate(twoDaysAgo.getDate() - 2)
if ((s.isNew() || c.valueChanged()) && c.value < twoDaysAgo)
c.error = 'תאריך עבר'
},
})
eventDate: Date = new Date()
@Fields.string({ inputType: 'time', caption: 'רלוונטי החל משעה' })
@DataControl({ width: '110' })
startTime = new Date().toLocaleTimeString('he-il', {
hour: '2-digit',
minute: '2-digit',
})
@Fields.integer({
caption: 'למשך כמה שעות הסיוע רלוונטי',
validate: (_, c) => {
if (_.isNew() || c.valueChanged()) {
if (getSite().requireValidUntil && !c.value) {
throw Error('ערך חסר')
}
if (getSite().requireValidUntil && +c.value > 72) {
throw Error('ערך גדול מדי, נא להזין עד 72 שעות')
}
}
},
})
relevantHours = getSite().requireValidUntil ? 0 : 12
@DataControl({ width: '240' })
@DateField({ caption: 'בתוקף עד', allowApiUpdate: false })
validUntil = new Date()
@Fields.json<GeocodeResult>()
addressApiResult: GeocodeResult | null = null
@Fields.string({
caption: 'מיקום מוצא *',
customInput: (c) =>
c.inputAddress(
(result, event: Task) =>
(event.addressApiResult = result.autoCompleteResult)
),
})
address = ''
@Fields.json<GeocodeResult>()
toAddressApiResult: GeocodeResult | null = null
@Fields.string({
caption: 'מיקום יעד *',
customInput: (c) =>
c.inputAddress(
(result, event: Task) =>
(event.toAddressApiResult = result.autoCompleteResult)
),
})
toAddress = ''
@Fields.number()
distance = 0
@PhoneField<Task>({
caption: 'טלפון ממלא הבקשה *',
...onlyDriverRules,
validate: (entity, ref) => {
if (entity.__disableValidation) return
if (
(entity.isNew() || ref.valueChanged()) &&
entity.getSite().useFillerInfo &&
!remult.isAllowed(Roles.dispatcher)
)
Validators.required(entity, ref)
},
})
requesterPhone1 = !remult.isAllowed(Roles.dispatcher)
? remult.user?.phone
: ''
@Fields.string({
caption: 'שם ממלא הבקשה',
...onlyDriverRules,
validate: requiredOnChange(
() =>
getSite().requireContactName &&
getSite().useFillerInfo &&
!remult.isAllowed(Roles.dispatcher)
),
})
requesterPhone1Description = !remult.isAllowed(Roles.dispatcher)
? remult.user?.name
: ''
@PhoneField<Task>({
caption: 'טלפון מוצא *',
...onlyDriverRules,
validate: requiredOnChange(() => true),
})
phone1 = ''
@Fields.string({
caption: 'איש קשר מוצא',
validate: requiredOnChange(() => getSite().requireContactName),
...onlyDriverRules,
})
phone1Description = ''
@DataControl({ visible: () => getSite().showTwoContacts })
@PhoneField<Task>({
caption: 'טלפון מוצא 2',
...onlyDriverRules,
})
phone2 = ''
@DataControl({ visible: () => getSite().showTwoContacts })
@Fields.string({
caption: 'איש קשר מוצא 2',
...onlyDriverRules,
})
phone2Description = ''
@PhoneField({
caption: 'טלפון ליעד',
validate: (entity, ref) => {
if (entity.__disableValidation) return
if (
(entity.isNew() || ref.valueChanged()) &&
(getSite().onlyAskForSecondAddress || getSite().requireContactName)
)
Validators.required(entity, ref)
},
...onlyDriverRules,
})
toPhone1 = ''
@Fields.string({
caption: 'איש קשר ליעד',
validate: requiredOnChange(() => getSite().requireContactName),
...onlyDriverRules,
})
tpPhone1Description = ''
@DataControl({ visible: () => getSite().showTwoContacts })
@PhoneField({
caption: 'טלפון ליעד 2',
...onlyDriverRules,
})
toPhone2 = ''
@DataControl({ visible: () => getSite().showTwoContacts })
@Fields.string({
caption: 'איש קשר ליעד 2',
...onlyDriverRules,
})
tpPhone2Description = ''
@Fields.string({
caption: 'מידע שיוצג רק לנהג המבצע ולמוקד',
...onlyDriverRules,
customInput: (x) => x.textarea(),
})
privateDriverNotes = ''
@CreatedAtField()
createdAt = new Date()
@Fields.string<Task>({
includeInApi: Roles.dispatcher,
allowApiUpdate: false,
caption: 'משתמש מוסיף',
displayValue: (u) => u.createUser?.name || '',
})
createUserId = getCurrentSiteUserId()
@Relations.toOne<Task, User>(() => User, 'createUserId')
createUser?: User
@Fields.string({
allowApiUpdate: false,
caption: 'נהג',
displayValue: (u) => u.driver?.name || '',
})
driverId = ''
@Relations.toOne<Task, User>(() => User, 'driverId')
driver?: User
@Fields.string({ allowApiUpdate: false })
statusNotes = ''
@DataControl<Task>({ visible: (t) => !t.isNew(), width: '70' })
@Fields.string({ caption: 'מזהה ', allowApiUpdate: false })
externalId = ''
@DataControl<Task>({
visible: (t) => t.eventBelongToOrgUser([Roles.trainee, Roles.dispatcher]),
})
@Fields.string({
caption: 'הערה פנימית לחמ"ל',
customInput: (x) => x.textarea(),
includeInApi: Roles.trainee,
})
internalComments = ''
@Fields.string<Task>({
caption: 'תמונה',
customInput: (c) => c.image(),
validate: (_, f) => {
if (_.__disableValidation) return
if (getSite().imageIsMandatory && (_.isNew() || f.valueChanged()))
Validators.required(_, f, 'אנא העלה תמונה')
},
})
imageId = ''
@Fields.integer<Task>({ includeInApi: false })
returnMondayStatus = -1
@Fields.string({ includeInApi: Roles.dispatcher })
editLink = createId()
@Fields.boolean({ allowApiUpdate: false, dbName: 'publicVisibleBoolean' })
publicVisible = false
@BackendMethod({ allowed: true })
static async makePublicVisible(id: string) {
if (!remult.context.availableTaskIds.includes(id))
throw Error('לא ניתן לבצע זאת למשימה זו')
if (!getSite().allowShareLink) throw Error('לא ניתן לבצע זאת')
const t = await repo(Task).findId(id)
t.publicVisible = true
await t.save()
await t.insertStatusChange('הפך לחשוף ציבורית')
}
@BackendMethod({ allowed: true })
static async getPublicTaskInfo(id: string) {
if (!getSite().allowShareLink) throw Error('פעולה לא מורשת')
const r = await repo(Task).findFirst({ id, publicVisible: true })
if (!r) throw Error('לא נמצאה משימה זו')
await r.insertStatusChange('צפייה ציבורית')
return r._.toApiJson()
}
@BackendMethod({ allowed: true })
static async getTaskSelfUpdateInfo(id: string) {
const r = await repo(Task).findFirst({
editLink: id,
taskStatus: taskStatus.active,
})
if (!r) throw Error('לא נמצאה משימה זו')
await r.insertStatusChange('צפייה למטרת עדכון על ידי מבקש')
return r._.toApiJson()
}
@BackendMethod({ allowed: true })
static async intakeUserId() {
if (remult.user) return getCurrentSiteUserId()
const user = await repo(User).findFirst({
phone: '0500000000',
deleted: false,
})
return user?.id
}
getTextMessagePhone() {
if (getSite().useFillerInfo && this.requesterPhone1)
return {
phone: this.requesterPhone1,
name: this.requesterPhone1Description,
}
return { phone: this.phone1, name: this.phone1Description }
}
@BackendMethod({ allowed: true })
static async SelfUpdateStatus(editLink: string, status: number) {
const r = await repo(Task).findFirst({
editLink,
taskStatus: taskStatus.active,
})
if (!r) throw Error('לא נמצאה משימה זו')
switch (status) {
case 1:
await r.insertStatusChange('עדיין רלוונטי', 'עודכן על ידי מבקש')
r.statusChangeDate = new Date()
break
case 21:
r.taskStatus = taskStatus.notRelevant
r.statusNotes = 'עודכן על ידי מבקש'
await r.insertStatusChange(r.taskStatus.caption, 'עודכן על ידי מבקש')
await r.save()
break
case 22:
try {
await r.insertStatusChange('לא לשלוח יותר SMS', 'עודכן על ידי מבקש')
await repo(BlockedPhone).insert({
phone: r.getTextMessagePhone().phone,
})
} catch (err) {
console.log(err)
}
break
}
return 'תודה על העדכון'
}
@BackendMethod({ allowed: Roles.admin })
static async markTasksForRelevanceCheck(ids: string[]) {
let i = 0
for (const task of await repo(Task).find({
where: { id: ids, taskStatus: taskStatus.active },
})) {
task.__disableValidation = true
await task.markForRelevanceCheck()
i++
}
return i
}
@BackendMethod({ allowed: Allow.authenticated })
async assignToMe(userId?: string) {
let assignUserId = getCurrentUserId(this.org)!
const assignedChangeType = 'שוייך לנהג'
if (userId) {
if ((await repo(User).count({ id: userId })) == 0)
throw Error('משתמש לא קיים')
if (
matchesCurrentUserId(userId, this.org) &&
!this.eventBelongToOrgUser(Roles.dispatcher)
)
throw Error('אינך רשאי לשייך לנהג אחר')
assignUserId = userId
} else {
if (
(await repo(Task).count({
driverId: assignUserId,
taskStatus: [taskStatus.assigned, taskStatus.driverPickedUp],
})) >= getSite().maxActiveTripsPerDriver
)
throw Error(
`ניתן להרשם במקביל לעד ${getSite().maxActiveTripsPerDriver} נסיעות`
)
if (
(await repo(TaskStatusChanges).count({
driverId: assignUserId,
what: assignedChangeType,
createdAt: {
$gt: new Date(new Date().getTime() - 1000 * 60 * 60),
},
})) >= 20
) {
throw Error('ניתן להרשם לעד 20 נסיעות בשעה')
}
}
await this._.reload()
if (this.driverId) throw Error('מתנדב אחר כבר לקח משימה זו')
if (!assignUserId) throw Error('משהו לא הסתדר בשיוך, מזהה נהג ריק')
this.driverId = assignUserId
this.taskStatus = taskStatus.assigned
this.statusNotes = ''
await this.insertStatusChange(assignedChangeType)
await this.save()
return this.getContactInfo()
}
async insertStatusChange(what: string, notes?: string) {
updateChannel(this.org).publish({
status: this.taskStatus.id,
message: what + ' - ' + this.getShortDescription(),
userId: getCurrentUserId(this.org)!,
action: what,
})
return await repo(TaskStatusChanges).insert({
org: this.org,
taskId: this.id,
what,
eventStatus: this.taskStatus,
notes,
driverId: this.driverId,
})
}
@Fields.string({
valueConverter: {
toDb: (x) => (x == null ? '' : x),
},
})
responsibleDispatcherId = ''
@Relations.toOne<Task, User>(() => User, 'responsibleDispatcherId')
responsibleDispatcher?: User
@BackendMethod({ allowed: Allow.authenticated })
async cancelAssignment(notes: string) {
this.checkAssignedToDriverOrDispatcher()
let hadDriverId = Boolean(this.driverId)
this.driverId = ''
this.taskStatus = taskStatus.active
this.statusNotes = notes
await this.insertStatusChange(
hadDriverId ? DriverCanceledAssign : 'נהג בחר לא לבצע',
notes
)
await this.save()
}
private checkAssignedToDriverOrDispatcher() {
const s = this.getSite()
if (!this.driverId && s.showContactToAnyDriver) return
if (
!matchesCurrentUserId(this.driverId, this.org) &&
!this.eventBelongToOrgUser(Roles.dispatcher)
)
throw new Error('נסיעה זו לא משוייכת לך')
}
@BackendMethod({ allowed: Allow.authenticated })
async noLongerRelevant(notes: string) {
if (!notes) throw Error('אנא הזן הערות, שנדע מה קרה')
this.checkAssignedToDriverOrDispatcher()
this.taskStatus = taskStatus.notRelevant
this.statusNotes = notes
await this.insertStatusChange(this.taskStatus.caption, notes)
await this.save()
}
@BackendMethod({ allowed: Roles.dispatcher })
async returnToDriver() {
if (!this.driverId) throw Error('לא נמצא נהג')
this.taskStatus = taskStatus.assigned
await this.insertStatusChange('מוקדן החזיר לנהג', 'על ידי מוקדן')
await this.save()
}
@BackendMethod({ allowed: Roles.dispatcher })
async returnToActive() {
this.driverId = ''
let action = 'מוקדן החזיר לפעיל'
if (this.taskStatus == taskStatus.draft) action = 'טיוטה אושרה'
this.taskStatus = taskStatus.active
await this.insertStatusChange(action, 'על ידי מוקדן')
await this.save()
}
@BackendMethod({ allowed: Roles.dispatcher })
async markAsDraft() {
this.driverId = ''
this.taskStatus = taskStatus.draft
await this.insertStatusChange('סמן כטיוטא', 'על ידי מוקדן')
await this.save()
}
@BackendMethod({ allowed: Roles.dispatcher })
async markForRelevanceCheck() {
this.taskStatus = taskStatus.relevanceCheck
await this.insertStatusChange(this.taskStatus.caption)
await this.save()
}
@BackendMethod({ allowed: Allow.authenticated })
async otherProblem(notes: string) {
if (!notes) throw Error('אנא הזן הערות, שנדע מה קרה')
this.checkAssignedToDriverOrDispatcher()
this.taskStatus = taskStatus.otherProblem
this.statusNotes = notes
await this.insertStatusChange(this.taskStatus.caption, notes)
await this.save()
}
@BackendMethod({ allowed: Allow.authenticated })
async completed(notes: string) {
this.checkAssignedToDriverOrDispatcher()
this.taskStatus = taskStatus.completed
this.statusNotes = notes
await this.insertStatusChange(this.taskStatus.caption, notes)
await this.save()
if (matchesCurrentUserId(this.driverId, this.org))
return await repo(Task)
.find({
where: {
driverId: this.driverId,
taskStatus: taskStatus.completed,
},
})
.then((x) =>
x.reduce(
(sum, t) => {
sum.rides++
sum.km += t.distance
return sum
},
{ rides: 0, km: 0 }
)
)
return undefined
}
@BackendMethod({ allowed: Allow.authenticated })
async completedStatusClickedByMistake() {
this.checkAssignedToDriverOrDispatcher()
if (
(await repo(TaskStatusChanges).count({
taskId: this.id,
eventStatus: taskStatus.driverPickedUp,
})) > 0
)
this.taskStatus = taskStatus.driverPickedUp
else this.taskStatus = taskStatus.assigned
this.statusNotes = ''
await this.insertStatusChange('עדכון סטטוס נלחץ בטעות')
await this.save()
}
@BackendMethod({ allowed: Allow.authenticated })
async driverPickedUp() {
this.checkAssignedToDriverOrDispatcher()
this.taskStatus = taskStatus.driverPickedUp
await this.insertStatusChange(this.taskStatus.caption)
await this.save()
}
@BackendMethod({ allowed: Allow.authenticated })
async pickedUpStatusClickedByMistake() {
this.checkAssignedToDriverOrDispatcher()
this.taskStatus = taskStatus.assigned
await this.insertStatusChange('נאסף בהצלחה נלחץ בטעות')
await this.save()
}
@BackendMethod({ allowed: Allow.authenticated })
async getContactInfo(): Promise<TaskContactInfo> {
if (Roles.dispatcher || matchesCurrentUserId(this.driverId, this.org))
return {
origin: [
{
phone: this.phone1,
formattedPhone: formatPhone(this.phone1),
name: this.phone1Description,
},
{
phone: this.phone2,
formattedPhone: formatPhone(this.phone2),
name: this.phone2Description,
},
],
target: [
{
phone: this.toPhone1,
formattedPhone: formatPhone(this.toPhone1),
name: this.tpPhone1Description,
},
{
phone: this.toPhone2,
formattedPhone: formatPhone(this.toPhone2),
name: this.tpPhone2Description,
},
],
}
return {
origin: [],
target: [],
}
}
async openEditDialog(ui: UITools, saved?: VoidFunction) {
const doLocks = !this.isNew()
if (doLocks)
try {
await Locks.lock(this.id, false)
} catch (err: any) {
if (remult.isAllowed(Roles.admin)) {
if (await ui.yesNoQuestion(err.message + ', לפתוח בכל זאת?')) {
await Locks.lock(this.id, true)
} else return
} else {
ui.error(err.message)
return
}
}
const e = this.$
ui.areaDialog({
title: 'פרטי נסיעה',
fields: [
[e.category!, e.urgency],
e.title,
e.address,
e.toAddress,
e.description,
e.privateDriverNotes,
[e.eventDate, e.startTime, e.relevantHours],
...(getSite().useFillerInfo
? [[e.requesterPhone1, e.requesterPhone1Description]]
: []),
[e.phone1, e.phone1Description],
[e.phone2, e.phone2Description],
[e.toPhone1, e.tpPhone1Description],
[e.toPhone2, e.tpPhone2Description],
e.imageId,
e.internalComments,
e.externalId,
],
ok: () =>
this.save().then(() => {
saved?.()
if (doLocks) Locks.unlock(this.id)
}),
cancel: () => {
this._.undoChanges()