tango-app-api-trax 3.4.0-soplink2-0 → 3.4.1-activitylog-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ import timeZone from 'dayjs/plugin/timezone.js';
18
18
  import utc from 'dayjs/plugin/utc.js';
19
19
  import { logger } from 'tango-app-api-middleware';
20
20
  import mongoose from 'mongoose';
21
- import { sendPushNotification } from 'tango-app-api-middleware';
21
+ import { sendPushNotification, sendAiPushNotification } from 'tango-app-api-middleware';
22
22
  // import * as planoService from '../services/planogram.service.js';
23
23
  import * as clusterServices from '../services/cluster.service.js';
24
24
  import * as teamsServices from '../services/teams.service.js';
@@ -68,7 +68,7 @@ export async function PCLchecklistCreationValidator( req, res, next ) {
68
68
  }
69
69
  }
70
70
 
71
- export async function PCLconfigCreation( req, res ) {
71
+ export async function PCLconfigCreationold( req, res ) {
72
72
  try {
73
73
  let requestData = req.body;
74
74
  let dateList = [ ...requestData.date ];
@@ -92,13 +92,570 @@ export async function PCLconfigCreation( req, res ) {
92
92
  req.body = requestData;
93
93
  PCLconfigCreation( req, res );
94
94
  }
95
- } else {
96
- return res.sendSuccess( { message: response.error } );
95
+ } else {
96
+ return res.sendSuccess( { message: response.error } );
97
+ }
98
+ }
99
+ } catch ( e ) {
100
+ logger.error( { function: 'PCLconfigCreation', error: e } );
101
+ return res.sendError( e, 500 );
102
+ }
103
+ };
104
+
105
+ export async function PCLconfigCreation( req, res ) {
106
+ try {
107
+ let requestData = req.body;
108
+ let getuniquechecklistquery = {
109
+ client_id: { $in: requestData.client_id },
110
+ type: 'checklist',
111
+ isdeleted: false,
112
+ publish: true,
113
+ };
114
+ let alreadyExist = [];
115
+ let getuniquechecklist = await CLconfig.find( getuniquechecklistquery );
116
+ if ( getuniquechecklist.length ) {
117
+ let checklistList = getuniquechecklist.map( ( ele ) => ele.checkListName );
118
+ logger.info( { checklistList: checklistList.toString() } );
119
+ for ( let [ dateIndex, date ] of requestData.date.entries() ) {
120
+ let currentday = dayjs( date ).format( 'dddd' );
121
+ let currentdate = dayjs( date ).format( 'YYYY-MM-DD' );
122
+ let currentdatedd = dayjs( date ).format( 'DD' );
123
+ let start = new Date( date );
124
+ let userTimezoneOffset = start.getTimezoneOffset() * 60000;
125
+ start = new Date( start.getTime() - userTimezoneOffset );
126
+ start.setUTCHours( 0, 0, 0, 0 );
127
+ let end = new Date( date );
128
+ end = new Date( end.getTime() - userTimezoneOffset );
129
+ end.setUTCHours( 23, 59, 59, 59 );
130
+ let validation;
131
+ validation = false;
132
+ let resultchecklist = [];
133
+ await Promise.all( getuniquechecklist.map( async ( element1 ) => {
134
+ validation = false;
135
+ let scheduledate = dayjs( element1.scheduleDate ).format( 'YYYY-MM-DD' );
136
+ if ( element1.schedule == 'daily' ) {
137
+ let newDate = dayjs.utc( element1.publishDate ).startOf( 'day' );
138
+ if ( element1.scheduleRepeatedDay[0] != '01' && newDate.format( 'YYYY-MM-DD' ) != currentdate ) {
139
+ let checkExists = await processedchecklist.findOne( { sourceCheckList_id: element1._id }, { date_string: 1 } );
140
+ if ( checkExists ) {
141
+ newDate = dayjs.utc( checkExists.date_string ).startOf( 'day' );
142
+ }
143
+ let cdate = dayjs.utc( currentdate ).startOf( 'day' );
144
+ let diff = parseInt( cdate.diff( newDate, 'day' ) );
145
+ diff = diff < 9 ? '0'+ diff : diff;
146
+ if ( diff == parseInt( element1.scheduleRepeatedDay[0] ) ) {
147
+ validation = true;
148
+ }
149
+ } else {
150
+ validation = true;
151
+ }
152
+ } else if ( [ 'weekly', 'weekday' ].includes( element1.schedule ) ) {
153
+ if ( element1.scheduleWeekDays.includes( currentday ) ) {
154
+ let newDate = dayjs.utc( element1.publishDate );
155
+ let endWeek = dayjs.utc( element1.publishDate ).endOf( 'week' );
156
+ if ( element1.scheduleRepeatedDay[0] != '01' && currentdate > endWeek.format( 'YYYY-MM-DD' ) ) {
157
+ let checkExists = await processedchecklist.findOne( { sourceCheckList_id: element1._id }, { date_string: 1 } );
158
+ if ( checkExists ) {
159
+ newDate = dayjs.utc( checkExists.date_string );
160
+ }
161
+ let startWeek = dayjs.utc( newDate ).startOf( 'week' );
162
+ let endWeek = dayjs.utc( newDate ).clone().endOf( 'week' );
163
+ let diff = parseInt( dayjs.utc( currentdate ).diff( startWeek, 'week' ) );
164
+ diff = diff < 9 ? '0'+diff : diff;
165
+ if ( diff == element1.scheduleRepeatedDay[0] || ( startWeek.format( 'YYYY-MM-DD' ) <= currentdate && endWeek.format( 'YYYY-MM-DD' ) >= currentdate ) ) {
166
+ validation = true;
167
+ }
168
+ } else {
169
+ validation = true;
170
+ }
171
+ }
172
+ } else if ( element1.schedule == 'monthly' ) {
173
+ if ( element1.scheduleRepeatedMonthSetup == 'day' && element1.scheduleRepeatedMonthWeek == currentdatedd ) {
174
+ validation = true;
175
+ } else if ( element1.scheduleRepeatedMonthSetup == 'date' ) {
176
+ let days = [];
177
+ let currDate = dayjs.utc( currentdate );
178
+ let dateDat = dayjs.utc( currDate ).startOf( 'month' );
179
+ while ( dateDat.month() === currDate.month() ) {
180
+ if ( dateDat.format( 'dddd' ) === element1.scheduleRepeatedMonthWeek.split( ' ' )[1] ) {
181
+ days.push( dateDat.format( 'YYYY-MM-DD' ) );
182
+ }
183
+ dateDat = dateDat.add( 1, 'day' );
184
+ }
185
+
186
+ if ( element1.scheduleRepeatedMonthWeek.split( ' ' )[0] == 5 ) {
187
+ if ( days[days.length -1] == currentdate ) {
188
+ validation = true;
189
+ }
190
+ } else {
191
+ if ( days[parseInt( element1.scheduleRepeatedMonthWeek.split( ' ' )[0] )-1] == currentdate ) {
192
+ validation = true;
193
+ }
194
+ }
195
+ } else if ( element1.scheduleRepeatedMonthSetup == 'specific' ) {
196
+ let currentdatesingleDigit = dayjs( currentdate ).format( 'D' );
197
+ if ( element1.specificDate.includes( parseInt( currentdatesingleDigit ) ) ) {
198
+ validation = true;
199
+ }
200
+ } else {
201
+ validation = false;
202
+ }
203
+
204
+ if ( validation ) {
205
+ validation = false;
206
+ let newDate = dayjs.utc( element1.publishDate );
207
+ let endMonth = newDate.endOf( 'month' );
208
+ if ( element1.scheduleRepeatedDay[0] != '01' && currentdate > endMonth.format( 'YYYY-MM-DD' ) ) {
209
+ let checkExists = await processedchecklist.findOne( { sourceCheckList_id: element1._id }, { date_string: 1 } );
210
+ if ( checkExists ) {
211
+ newDate = dayjs( checkExists.date_string );
212
+ }
213
+
214
+ let startMonth = newDate.startOf( 'month' );
215
+ let endMonth = newDate.clone().endOf( 'month' );
216
+
217
+ let diff = parseInt( dayjs.utc( currentdate ).diff( startMonth, 'month' ) );
218
+ diff = diff < 9 ? '0'+diff : diff;
219
+
220
+ if ( diff == parseInt( element1.scheduleRepeatedDay[0] ) || ( startMonth.format( 'YYYY-MM-DD' ) <= currentdate && endMonth.format( 'YYYY-MM-DD' ) >= currentdate ) ) {
221
+ validation = true;
222
+ }
223
+ } else {
224
+ validation = true;
225
+ }
226
+ }
227
+ } else if ( element1.schedule == 'onetime' ) {
228
+ if ( scheduledate == currentdate ) {
229
+ resultchecklist.push( element1._id );
230
+ }
231
+ } else {
232
+ let startDate = dayjs.utc( element1.configStartDate ).format( 'YYYY-MM-DD' );
233
+ let endDate = dayjs.utc( element1.configEndDate ).format( 'YYYY-MM-DD' );
234
+
235
+ if ( startDate <= currentdate && endDate >= currentdate ) {
236
+ if ( !element1?.specificDate?.length ) {
237
+ resultchecklist.push( element1._id );
238
+ } else {
239
+ if ( element1?.specificDate.includes( dayjs( currentdate ).format( 'DD-MM-YYYY' ) ) ) {
240
+ resultchecklist.push( element1._id );
241
+ }
242
+ }
243
+ }
244
+ }
245
+ if ( ![ 'onetime', 'range' ].includes( element1.schedule ) ) {
246
+ if ( validation ) {
247
+ let startDate = element1?.configStartDate ? dayjs.utc( element1?.configStartDate ).format( 'YYYY-MM-DD' ) : '';
248
+ let endDate = element1?.configEndDate ? dayjs.utc( element1?.configEndDate ).format( 'YYYY-MM-DD' ) : '';
249
+ if ( !startDate && !endDate || ( startDate && ( startDate == currentdate || startDate < currentdate ) ) && endDate == '' ) {
250
+ resultchecklist.push( element1._id );
251
+ }
252
+ if ( endDate != '' && startDate <= currentdate && endDate >= currentdate ) {
253
+ resultchecklist.push( element1._id );
254
+ }
255
+ }
256
+ }
257
+ } ) );
258
+ if ( resultchecklist.length ) {
259
+ await Promise.all( resultchecklist.map( async ( element2 ) => {
260
+ let getCLconfig = getuniquechecklist.find( ( checklist ) => checklist._id.toString() == element2.toString() );
261
+ if ( getCLconfig ) {
262
+ let startTimeIso; let endTimeIso;
263
+ startTimeIso = dayjs.utc( `${currentdate} ${getCLconfig.scheduleStartTime}`, 'YYYY-MM-DD hh:mm A' );
264
+ endTimeIso = dayjs.utc( `${currentdate} ${getCLconfig.scheduleEndTime}`, 'YYYY-MM-DD hh:mm A' );
265
+ let insertdata = {};
266
+ insertdata.date_iso = new Date( currentdate );
267
+ insertdata.date_string = currentdate;
268
+ insertdata.sourceCheckList_id = getCLconfig._id;
269
+ insertdata.checkListName = getCLconfig.checkListName;
270
+ insertdata.checkListDescription = getCLconfig.checkListDescription;
271
+ insertdata.publish = getCLconfig.publish;
272
+ insertdata.scheduleStartTime = getCLconfig.scheduleStartTime;
273
+ insertdata.scheduleStartTime_iso = startTimeIso.format();
274
+ insertdata.scheduleEndTime = getCLconfig.scheduleEndTime;
275
+ insertdata.scheduleEndTime_iso = endTimeIso.format();
276
+ insertdata.allowedOverTime = getCLconfig.allowedOverTime;
277
+ insertdata.allowedStoreLocation = getCLconfig.allowedStoreLocation;
278
+ insertdata.client_id = getCLconfig.client_id;
279
+ insertdata.createdBy = new ObjectId( getCLconfig.createdBy );
280
+ insertdata.createdByName = getCLconfig.createdByName;
281
+ insertdata.checkListType = getCLconfig.checkListType;
282
+ insertdata.storeCount = getCLconfig.storeCount;
283
+ insertdata.questionCount = getCLconfig.questionCount;
284
+ insertdata.publishDate = getCLconfig.publishDate;
285
+ insertdata.locationCount = getCLconfig.locationCount;
286
+ insertdata.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
287
+ insertdata.allowedMultiSubmit = getCLconfig.allowedMultiSubmit;
288
+ insertdata.rawImageUpload = getCLconfig.rawImageUpload || false;
289
+ let collectSections = [];
290
+ let sectionQuery = [];
291
+ sectionQuery.push( {
292
+ $match: {
293
+ checkListId: element2,
294
+ isdeleted: false,
295
+ },
296
+ } );
297
+ let getSections = await CLquestions.aggregate( sectionQuery );
298
+ if ( getSections.length || [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall', 'drinking', 'bagdetection' ].includes( getCLconfig.checkListType ) ) {
299
+ if ( getSections.length ) {
300
+ for ( let element3 of getSections ) {
301
+ let collectQuestions = {};
302
+ collectQuestions.section_id = element3._id;
303
+ collectQuestions.sectionName = element3.section;
304
+ collectQuestions.questions = element3.question;
305
+ collectSections.push( collectQuestions );
306
+ }
307
+ }
308
+ insertdata.questionAnswers = collectSections;
309
+ insertdata.updatedAt = new Date();
310
+ let insertdataquery = {};
311
+ insertdataquery.date_string = insertdata.date_string;
312
+ insertdataquery.date_iso = insertdata.date_iso;
313
+ insertdataquery.client_id = insertdata.client_id;
314
+ insertdataquery.sourceCheckList_id = insertdata.sourceCheckList_id;
315
+ insertdataquery.startTime = { $exists: true };
316
+ let checkchecklist = await PCLconfig.findOne( insertdataquery );
317
+ if ( !checkchecklist ) {
318
+ delete insertdataquery.startTime;
319
+ let updatedchecklist;
320
+ let checklistDetails = await PCLconfig.findOne( insertdataquery );
321
+ if ( !checklistDetails ) {
322
+ updatedchecklist = await PCLconfig.insert( insertdata );
323
+ } else {
324
+ await PCLconfig.updateOne( { _id: checklistDetails._id }, insertdata );
325
+ updatedchecklist = checklistDetails;
326
+ }
327
+ if ( updatedchecklist ) {
328
+ let getquestionQuery = [];
329
+ getquestionQuery.push( {
330
+ $match: {
331
+ checkListId: element2,
332
+ isdeleted: false,
333
+ },
334
+ } );
335
+ let allQuestion = await CLassign.aggregate( getquestionQuery );
336
+ if ( allQuestion.length && getCLconfig.checkListType == 'custom' ) {
337
+ let assignList = [];
338
+ if ( getCLconfig.coverage == 'store' ) {
339
+ let clusterList = allQuestion.filter( ( ele ) => ele?.clusterName ).map( ( item ) => item.assignId );
340
+ if ( clusterList.length ) {
341
+ let clusterDetails = await clusterServices.findcluster( { _id: { $in: clusterList } } );
342
+ if ( clusterDetails.length ) {
343
+ let idList = clusterDetails.flatMap( ( item ) => item.stores.map( ( ele ) => ele.store ) );
344
+ let getStoreDetails = await storeService.find( { _id: { $in: idList } } );
345
+ if ( getStoreDetails.length ) {
346
+ assignList = await Promise.all( getStoreDetails.map( async ( store ) => {
347
+ let userDetails = await userService.findOne( { email: store?.spocDetails?.[0]?.email, clientId: store.clientId } );
348
+ if ( !userDetails ) {
349
+ let data = {
350
+ clientId: store.clientId,
351
+ userName: store.spocDetails?.[0]?.name,
352
+ mobileNumber: store.spocDetails?.[0]?.phone || '',
353
+ email: store.spocDetails[0].email,
354
+ password: '5dqFKAJj29PsV6P+kL+3Dw==',
355
+ role: 'user',
356
+ userType: 'client',
357
+ rolespermission: [
358
+ {
359
+ featureName: 'Global',
360
+ modules: [
361
+ {
362
+ name: 'Store',
363
+ isAdd: false,
364
+ isEdit: false,
365
+
366
+ },
367
+ {
368
+ name: 'User',
369
+ isAdd: false,
370
+ isEdit: false,
371
+
372
+ },
373
+ {
374
+ name: 'Camera',
375
+ isAdd: false,
376
+ isEdit: false,
377
+
378
+ },
379
+ {
380
+ name: 'Configuration',
381
+ isAdd: false,
382
+ isEdit: false,
383
+
384
+ },
385
+ {
386
+ name: 'Subscription',
387
+ isAdd: false,
388
+ isEdit: false,
389
+
390
+ },
391
+ {
392
+ name: 'Billing',
393
+ isAdd: false,
394
+ isEdit: false,
395
+
396
+ },
397
+ ],
398
+ },
399
+ {
400
+ featurName: 'TangoEye',
401
+ modules: [
402
+ {
403
+ name: 'ZoneTag',
404
+ isAdd: false,
405
+ isEdit: false,
406
+
407
+ },
408
+ ],
409
+ },
410
+ {
411
+ featurName: 'TangoTrax',
412
+ modules: [
413
+ {
414
+ name: 'checklist',
415
+ isAdd: false,
416
+ isEdit: false,
417
+
418
+ },
419
+ {
420
+ name: 'Task',
421
+ isAdd: false,
422
+ isEdit: false,
423
+
424
+ },
425
+ ],
426
+ },
427
+ ],
428
+ };
429
+ userDetails = await userService.create( data );
430
+ }
431
+ let data = {
432
+ store_id: store?.storeId,
433
+ storeName: store?.storeName,
434
+ userId: userDetails._id,
435
+ userName: userDetails.userName,
436
+ userEmail: userDetails.email,
437
+ userPhone: userDetails?.mobileNumber,
438
+ city: store?.storeProfile?.city,
439
+ country: store?.storeProfile?.country,
440
+ checkFlag: true,
441
+ checkListId: getCLconfig._id,
442
+ checkListName: getCLconfig.checkListName,
443
+ client_id: getCLconfig.client_id,
444
+ };
445
+ return data;
446
+ } ) );
447
+ }
448
+ }
449
+ }
450
+ allQuestion = allQuestion.filter( ( ele ) => !clusterList.includes( ele.assignId ) );
451
+ }
452
+ if ( getCLconfig.coverage == 'user' ) {
453
+ let teamsList = allQuestion.filter( ( ele ) => ele?.teamName ).map( ( item ) => item.assignId );
454
+ if ( teamsList.length ) {
455
+ let teamDetails = await teamsServices.findteams( { _id: { $in: teamsList } } );
456
+ if ( teamDetails.length ) {
457
+ let idList = [ ...teamDetails.flatMap( ( item ) => item.users.map( ( ele ) => ele.userId ) ), ...teamDetails.flatMap( ( item ) => item.Teamlead.map( ( ele ) => ele.userId ) ) ];
458
+ let getUserDetails = await userService.find( { _id: { $in: idList } } );
459
+ if ( getUserDetails.length ) {
460
+ assignList = getUserDetails.map( ( user ) => {
461
+ let data = {
462
+ store_id: '',
463
+ storeName: '',
464
+ userId: user._id,
465
+ userName: user.userName,
466
+ userEmail: user.email,
467
+ userPhone: user?.mobileNumber,
468
+ city: '',
469
+ country: '',
470
+ checkFlag: true,
471
+ checkListId: getCLconfig._id,
472
+ checkListName: getCLconfig.checkListName,
473
+ client_id: getCLconfig.client_id,
474
+ };
475
+ return data;
476
+ } );
477
+ }
478
+ }
479
+ }
480
+ allQuestion = allQuestion.filter( ( ele ) => !teamsList.includes( ele.assignId ) );
481
+ }
482
+ allQuestion = [ ...allQuestion, ...assignList ];
483
+ let userIdList = [];
484
+ for ( let element4 of allQuestion ) {
485
+ if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
486
+ let query;
487
+ if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
488
+ let startDate; let endDate;
489
+ if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
490
+ startDate = dayjs.utc( currentdate ).clone().startOf( 'week' );
491
+ endDate = dayjs.utc( currentdate ).clone().endOf( 'week' );
492
+ } else {
493
+ startDate = dayjs.utc( currentdate ).clone().startOf( 'month' );
494
+ endDate = dayjs.utc( currentdate ).clone().endOf( 'month' );
495
+ }
496
+ query = {
497
+ sourceCheckList_id: getCLconfig._id,
498
+ $or: [ {
499
+ checklistStatus: { $in: [ 'submit' ] } },
500
+ { submitTime: { $exists: true } },
501
+ ],
502
+ userId: element4.userId,
503
+ store_id: element4.store_id,
504
+ $and: [ {
505
+ date_iso: {
506
+ $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
507
+ $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
508
+ } ],
509
+ };
510
+ } else {
511
+ query = {
512
+ sourceCheckList_id: getCLconfig._id,
513
+ $or: [ {
514
+ checklistStatus: { $in: [ 'submit' ] } },
515
+ { submitTime: { $exists: true } },
516
+ ],
517
+ userId: element4.userId,
518
+ store_id: element4.store_id,
519
+ $and: [ {
520
+ date_iso: {
521
+ $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
522
+ $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ) },
523
+ } ],
524
+ };
525
+ }
526
+ let getsubmitDetails = await processedchecklist.find( query );
527
+ if ( getsubmitDetails.length ) {
528
+ userIdList.push( element4._id );
529
+ continue;
530
+ }
531
+ }
532
+ delete element4._id;
533
+ delete element4.checkFlag;
534
+ delete element4.isdeleted;
535
+ delete element4.createdAt;
536
+ delete element4.updatedAt;
537
+ element4.checkListId = updatedchecklist._id;
538
+ element4.checkListName = getCLconfig.checkListName;
539
+ element4.checkListDescription = getCLconfig.checkListDescription;
540
+ element4.date_iso = new Date( currentdate );
541
+ element4.date_string = currentdate;
542
+ element4.allowedOverTime = getCLconfig.allowedOverTime;
543
+ element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
544
+ element4.scheduleStartTime = getCLconfig.scheduleStartTime;
545
+ element4.scheduleStartTime_iso = startTimeIso.format();
546
+ element4.scheduleEndTime = getCLconfig.scheduleEndTime;
547
+ element4.scheduleEndTime_iso = endTimeIso.format();
548
+ element4.createdBy = new ObjectId( getCLconfig.createdBy );
549
+ element4.createdByName = getCLconfig.createdByName;
550
+ element4.sourceCheckList_id = getCLconfig._id;
551
+ element4.checkListType = getCLconfig.checkListType;
552
+ element4.storeCount = getCLconfig.storeCount;
553
+ element4.questionCount = getCLconfig.questionCount;
554
+ element4.publishDate = getCLconfig.publishDate;
555
+ element4.locationCount = getCLconfig.locationCount;
556
+ element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
557
+ element4.approvalEnable = getCLconfig.approver.length ? true : false;
558
+ element4.remainder = getCLconfig?.remainder || [];
559
+ // if ( getCLconfig?.isPlano ) {
560
+ // let planoDetails = await planoService.findOne( { storeId: element4.store_id, clientId: getCLconfig.client_id }, { _id: 1 } );
561
+ // element4.planoId = planoDetails?._id;
562
+ // element4.isPlano = getCLconfig?.isPlano;
563
+ // }
564
+ element4.rawImageUpload = getCLconfig?.rawImageUpload || false;
565
+ }
566
+ if ( userIdList.length ) {
567
+ allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
568
+ }
569
+ if ( allQuestion ) {
570
+ let assigndeletequery = {};
571
+ assigndeletequery.date_string = insertdata.date_string;
572
+ assigndeletequery.date_iso = insertdata.date_iso;
573
+ assigndeletequery.client_id = insertdata.client_id;
574
+ assigndeletequery.checkListId = updatedchecklist._id;
575
+ assigndeletequery.checklistStatus = { $nin: [ 'submit' ] };
576
+ // if (getCLconfig.scheduleRepeatedType == 'range') {
577
+ // allQuestion.forEach(async item => {
578
+ // assigndeletequery.userId = item.userId
579
+ // await processedchecklist.deleteMany(assigndeletequery);
580
+ // await processedchecklist.insertMany(item);
581
+ // logger.info({function:"PCLconfigCreation Range",query:assigndeletequery})
582
+ // })
583
+ // }
584
+ // else {
585
+ await processedchecklist.deleteMany( assigndeletequery );
586
+ logger.info( { checklistId: getCLconfig._id, insertedCount: allQuestion.length } );
587
+ await processedchecklist.insertMany( allQuestion );
588
+ logger.info( { function: 'PCLconfigCreation', query: assigndeletequery } );
589
+ // }
590
+ }
591
+ } else {
592
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall', 'drinking', 'bagdetection' ].includes( getCLconfig.checkListType ) ) {
593
+ let storeNameList = allQuestion.map( ( item ) => item.store_id );
594
+ let storeDetails = await storeService.find( { clientId: getCLconfig.client_id, status: 'active', ...( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) ? { storeId: { $in: storeNameList } } : {} }, { storeId: 1 } );
595
+ let storeList = storeDetails.map( ( store ) => store.storeId );
596
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
597
+ allQuestion = allQuestion.filter( ( ele ) => storeList.includes( ele?.store_id ) );
598
+ } else {
599
+ allQuestion = storeDetails.map( ( item ) => {
600
+ return {
601
+ store_id: item.storeId,
602
+ };
603
+ } );
604
+ }
605
+ let data = {
606
+ checkListId: updatedchecklist._id,
607
+ checkListName: getCLconfig.checkListName,
608
+ date_iso: new Date( currentdate ),
609
+ date_string: currentdate,
610
+ allowedOverTime: getCLconfig.allowedOverTime,
611
+ allowedStoreLocation: getCLconfig.allowedStoreLocation,
612
+ checkListDescription: getCLconfig.checkListDescription,
613
+ scheduleStartTime: getCLconfig.scheduleStartTime,
614
+ scheduleStartTime_iso: startTimeIso.format(),
615
+ scheduleEndTime: getCLconfig.scheduleEndTime,
616
+ scheduleEndTime_iso: endTimeIso.format(),
617
+ createdBy: new ObjectId( getCLconfig.createdBy ),
618
+ createdByName: getCLconfig.createdByName,
619
+ sourceCheckList_id: getCLconfig._id,
620
+ checkListType: getCLconfig.checkListType,
621
+ storeCount: getCLconfig.storeCount,
622
+ questionCount: getCLconfig.questionCount,
623
+ publishDate: getCLconfig.publishDate,
624
+ locationCount: getCLconfig.locationCount,
625
+ scheduleRepeatedType: getCLconfig.scheduleRepeatedType,
626
+ storeCount: storeDetails.length,
627
+ client_id: getCLconfig.client_id,
628
+ aiStoreList: allQuestion.length ? allQuestion.map( ( store ) => store.store_id ) : [],
629
+ };
630
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
631
+ let processData = {
632
+ aiStoreList: allQuestion.length ? allQuestion.map( ( store ) => {
633
+ return { storeName: store.storeName, storeId: store.store_id, events: store.events };
634
+ } ) : [],
635
+ aiConfig: getCLconfig?.aiConfig,
636
+ };
637
+ await PCLconfig.updateOne( { _id: updatedchecklist._id }, processData );
638
+ }
639
+ await processedchecklist.updateOne( { date_string: currentdate, checkListId: updatedchecklist._id, sourceCheckList_id: getCLconfig._id, checkListType: getCLconfig.checkListType }, data );
640
+ }
641
+ }
642
+ }
643
+ } else {
644
+ alreadyExist.push( { sourceCheckList_id: insertdata.sourceCheckList_id, checkListName: insertdata.checkListName } );
645
+ }
646
+ }
647
+ }
648
+ } ) );
649
+ }
650
+
651
+ if ( dateIndex == 0 ) {
652
+ res.sendSuccess( { message: 'Processed Daily Check List Created Successfully', error: alreadyExist } );
653
+ }
97
654
  }
98
655
  }
99
656
  } catch ( e ) {
100
657
  logger.error( { function: 'PCLconfigCreation', error: e } );
101
- return res.sendError( e, 500 );
658
+ // return res.sendError( e, 500 );/
102
659
  }
103
660
  };
104
661
 
@@ -304,7 +861,7 @@ async function insertData( requestData ) {
304
861
  },
305
862
  } );
306
863
  let getSections = await CLquestions.aggregate( sectionQuery );
307
- if ( getSections.length || [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
864
+ if ( getSections.length || [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall', 'drinking', 'bagdetection' ].includes( getCLconfig.checkListType ) ) {
308
865
  if ( getSections.length ) {
309
866
  for ( let element3 of getSections ) {
310
867
  let collectQuestions = {};
@@ -342,7 +899,7 @@ async function insertData( requestData ) {
342
899
  },
343
900
  } );
344
901
  let allQuestion = await CLassign.aggregate( getquestionQuery );
345
- if ( allQuestion.length ) {
902
+ if ( allQuestion.length && getCLconfig.checkListType == 'custom' ) {
346
903
  let assignList = [];
347
904
  if ( getCLconfig.coverage == 'store' ) {
348
905
  let clusterList = allQuestion.filter( ( ele ) => ele?.clusterName ).map( ( item ) => item.assignId );
@@ -597,8 +1154,19 @@ async function insertData( requestData ) {
597
1154
  // }
598
1155
  }
599
1156
  } else {
600
- if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
601
- let storeDetails = await storeService.find( { clientId: getCLconfig.client_id, status: 'active' }, { storeId: 1 } );
1157
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection', 'customerunattended', 'staffleftinthemiddle', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall', 'drinking', 'bagdetection' ].includes( getCLconfig.checkListType ) ) {
1158
+ let storeNameList = allQuestion.map( ( item ) => item.store_id );
1159
+ let storeDetails = await storeService.find( { clientId: getCLconfig.client_id, status: 'active', ...( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) ? { storeId: { $in: storeNameList } } : {} }, { storeId: 1 } );
1160
+ let storeList = storeDetails.map( ( store ) => store.storeId );
1161
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
1162
+ allQuestion = allQuestion.filter( ( ele ) => storeList.includes( ele?.store_id ) );
1163
+ } else {
1164
+ allQuestion = storeDetails.map( ( item ) => {
1165
+ return {
1166
+ store_id: item.storeId,
1167
+ };
1168
+ } );
1169
+ }
602
1170
  let data = {
603
1171
  checkListId: updatedchecklist._id,
604
1172
  checkListName: getCLconfig.checkListName,
@@ -606,6 +1174,7 @@ async function insertData( requestData ) {
606
1174
  date_string: currentdate,
607
1175
  allowedOverTime: getCLconfig.allowedOverTime,
608
1176
  allowedStoreLocation: getCLconfig.allowedStoreLocation,
1177
+ checkListDescription: getCLconfig.checkListDescription,
609
1178
  scheduleStartTime: getCLconfig.scheduleStartTime,
610
1179
  scheduleStartTime_iso: startTimeIso.format(),
611
1180
  scheduleEndTime: getCLconfig.scheduleEndTime,
@@ -621,8 +1190,17 @@ async function insertData( requestData ) {
621
1190
  scheduleRepeatedType: getCLconfig.scheduleRepeatedType,
622
1191
  storeCount: storeDetails.length,
623
1192
  client_id: getCLconfig.client_id,
624
- aiStoreList: storeDetails ? storeDetails.map( ( store ) => store.storeId ) : [],
1193
+ aiStoreList: allQuestion.length ? allQuestion.map( ( store ) => store.store_id ) : [],
625
1194
  };
1195
+ if ( [ 'storeopenandclose', 'mobileusagedetection', 'cleaning', 'scrum' ].includes( getCLconfig.checkListType ) ) {
1196
+ let processData = {
1197
+ aiStoreList: allQuestion.length ? allQuestion.map( ( store ) => {
1198
+ return { storeName: store.storeName, storeId: store.store_id, events: store.events };
1199
+ } ) : [],
1200
+ aiConfig: getCLconfig?.aiConfig,
1201
+ };
1202
+ await PCLconfig.updateOne( { _id: updatedchecklist._id }, processData );
1203
+ }
626
1204
  // await processedchecklist.create( data );
627
1205
  await processedchecklist.updateOne( { date_string: currentdate, checkListId: updatedchecklist._id, sourceCheckList_id: getCLconfig._id, checkListType: getCLconfig.checkListType }, data );
628
1206
  }
@@ -1433,6 +2011,37 @@ export async function getPDFCSVChecklistDetails( req, res ) {
1433
2011
  }
1434
2012
 
1435
2013
 
2014
+ export async function AiPushNotificationAlert( req, res ) {
2015
+ try {
2016
+ console.log( req.body );
2017
+ let findAichecklist = await PCLconfig.findOne( { checkListType: req.body.checkListType, client_id: req.body.clientId, date_string: req.body.Date }, { aiConfig: 1 } );
2018
+ if ( findAichecklist.aiConfig&&findAichecklist.aiConfig.alerts&&findAichecklist.aiConfig.alerts.users&&findAichecklist.aiConfig.alerts.users.length>0 ) {
2019
+ console.log( findAichecklist.aiConfig.alerts.users );
2020
+ for ( let user of findAichecklist.aiConfig.alerts.users ) {
2021
+ let findOneUser = await userService.findOne( { email: user }, { fcmToken: 1 } );
2022
+ console.log( findOneUser );
2023
+ if ( findOneUser&&findOneUser.fcmToken&&findOneUser.fcmToken!='' ) {
2024
+ console.log( findOneUser.fcmToken );
2025
+ try {
2026
+ await sendPushNotification( req.body.title, req.body.description, findOneUser.fcmToken );
2027
+ } catch ( e ) {
2028
+ logger.error( {
2029
+ message: 'push notification',
2030
+ error: e,
2031
+ details: data,
2032
+ } );
2033
+ }
2034
+ } ;
2035
+ }
2036
+ return res.sendSuccess( 'Push notification send successfully' );
2037
+ }
2038
+ } catch ( e ) {
2039
+ logger.error( { function: 'AiPushNotificationAlert', error: e } );
2040
+ return res.sendError( e, 500 );
2041
+ }
2042
+ }
2043
+
2044
+
1436
2045
  export async function taskPushNotification( req, res ) {
1437
2046
  try {
1438
2047
  let query = [ {
@@ -1644,3 +2253,59 @@ async function getUserToken( clientId, userEmail ) {
1644
2253
  return false;
1645
2254
  }
1646
2255
  }
2256
+
2257
+ export async function internalAISendPushNotification( req, res ) {
2258
+ try {
2259
+ let requestData = req.body;
2260
+ // if ( !requestData.clientId ) {
2261
+ // return res.sendError( 'clientId is Required', 400 );
2262
+ // }
2263
+ if ( !( requestData?.email || requestData?.storeId ) ) {
2264
+ return res.sendError( 'Email or StoreId is Required', 400 );
2265
+ }
2266
+
2267
+ if ( !requestData.title ) {
2268
+ return res.sendError( 'Title is Required', 400 );
2269
+ }
2270
+
2271
+ if ( !requestData.description ) {
2272
+ return res.sendError( 'Description is Required', 400 );
2273
+ }
2274
+
2275
+ let userData;
2276
+ if ( requestData.email && requestData.email !='' ) {
2277
+ // fcmToken = await getUserToken( requestData.clientId, requestData.email );
2278
+ // userData = await userService.findOne( { clientId: requestData.clientId, email: requestData.email }, { fcmToken: 1, loginFrom: 1 } );
2279
+ userData = await userService.findOne( { email: requestData.email }, { fcmToken: 1, loginFrom: 1 } );
2280
+ } else {
2281
+ // let storeData = await storeService.findOne( { clientId: requestData.clientId, storeId: requestData.storeId }, { spocDetails: 1 } );
2282
+ let storeData = await storeService.findOne( { storeId: requestData.storeId }, { spocDetails: 1 } );
2283
+ if ( storeData && storeData.spocDetails.length > 0 && storeData.spocDetails[0].email ) {
2284
+ // fcmToken = await getUserToken( storeData.spocDetails[0].email );
2285
+ // userData = await userService.findOne( { clientId: requestData.clientId, email: requestData.email }, { fcmToken: 1, loginFrom: 1 } );
2286
+ userData = await userService.findOne( { email: requestData.email }, { fcmToken: 1, loginFrom: 1 } );
2287
+ }
2288
+ }
2289
+ if ( !userData ) {
2290
+ return res.sendSuccess( 'Notification Send Successfully' );
2291
+ }
2292
+ let custom = {
2293
+ title: requestData.title,
2294
+ body: requestData.description,
2295
+ type: req.body?.type,
2296
+ storeId: req.body?.storeId,
2297
+ date: req.body?.date,
2298
+ clientId: req.body?.clientId,
2299
+ };
2300
+ let responseData = await sendAiPushNotification( userData.fcmToken, custom, userData.loginFrom );
2301
+ if ( responseData ) {
2302
+ return res.sendSuccess( 'Notification Send Successfully' );
2303
+ } else {
2304
+ return res.sendSuccess( 'Notification Send Successfully' );
2305
+ }
2306
+ } catch ( e ) {
2307
+ logger.error( { error: e, function: 'internalAISendPushNotification' } );
2308
+ if ( e.name === 'ValidationError' ) res.sendBadRequest( e );
2309
+ else res.sendError( e, 500 );
2310
+ }
2311
+ };