tango-app-api-trax 3.2.1 → 3.3.1-airtalai-0

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.
@@ -21,6 +21,8 @@ import utc from 'dayjs/plugin/utc.js';
21
21
  import isEqual from 'lodash/isEqual.js';
22
22
  dayjs.extend( utc );
23
23
  dayjs.extend( customParseFormat );
24
+ import * as clusterServices from '../services/cluster.service.js';
25
+ import * as teamsServices from '../services/teams.service.js';
24
26
 
25
27
 
26
28
  export const checklist = async ( req, res ) => {
@@ -54,6 +56,7 @@ export const checklist = async ( req, res ) => {
54
56
  $project: {
55
57
  checkList: { $toLower: '$checkListName' },
56
58
  checkListName: 1,
59
+ coverage: 1,
57
60
  createdBy: 1,
58
61
  userName: { $toLower: '$createdByName' },
59
62
  createdByName: 1,
@@ -124,7 +127,6 @@ export const checklist = async ( req, res ) => {
124
127
  }
125
128
  };
126
129
 
127
-
128
130
  export const create = async ( req, res ) => {
129
131
  try {
130
132
  let inputBody = req.body;
@@ -246,9 +248,13 @@ export const create = async ( req, res ) => {
246
248
  }
247
249
  if ( answer.showLinked ) {
248
250
  if ( nestedIndex != -1 ) {
249
- section.questions[qIdx].answers[nestedIndex].nestedQuestion.push( answer.linkedQuestion );
251
+ if ( !section.questions[qIdx].answers[nestedIndex].nestedQuestion.includes( answer.linkedQuestion ) ) {
252
+ section.questions[qIdx].answers[nestedIndex].nestedQuestion.push( answer.linkedQuestion );
253
+ }
250
254
  } else {
251
- section.questions[qIdx].answers[index].nestedQuestion.push( answer.linkedQuestion );
255
+ if ( !section.questions[qIdx].answers[index].nestedQuestion.includes( answer.linkedQuestion ) ) {
256
+ section.questions[qIdx].answers[index].nestedQuestion.push( answer.linkedQuestion );
257
+ }
252
258
  }
253
259
  let nestedLinkedQuestion = section.questions.find( ( item ) => item.qno == answer.linkedQuestion );
254
260
  if ( nestedLinkedQuestion ) {
@@ -388,9 +394,29 @@ export const getConfigDetails = async ( req, res ) => {
388
394
  result.checkListDetails.scheduleStartTime = result.openTime;
389
395
  result.checkListDetails.scheduleEndTime = result.closeTime;
390
396
  }
391
- let removedUsers = await assignedService.find( { checkFlag: false, checkListId: storechecklistdetails._id }, { _id: 1 } );
392
- removedUsers = removedUsers?.map( ( item ) => item._id );
393
- result.checkListDetails = { ...result.checkListDetails, ...{ sections: sectionList }, ...{ assignedUsers: [] }, ...{ removedUsers: removedUsers } };
397
+ let query = {
398
+ checkListId: storechecklistdetails._id,
399
+ ...( storechecklistdetails.coverage == 'store' ) ? { $or: [ { store_id: { $exists: true } }, { clusterName: { $exists: true } } ] } : { $or: [ { userEmail: { $exists: true } }, { teamName: { $exists: true } } ] },
400
+ };
401
+ let assignList = await assignedService.find( query, { _id: 1, store_id: 1, clusterName: 1, userEmail: 1, teamName: 1, assignId: 1 } );
402
+ let singleAssign;
403
+ let groupAssign;
404
+ if ( storechecklistdetails.coverage == 'store' ) {
405
+ singleAssign = assignList.filter( ( item ) => typeof item?.store_id != 'undefined' && item?.store_id != '' ).map( ( item ) => {
406
+ return { id: item.assignId, type: 'store' };
407
+ } );
408
+ groupAssign = assignList.filter( ( item ) => typeof item?.clusterName != 'undefined' && item?.clusterName != '' ).map( ( item ) => {
409
+ return { id: item.assignId, type: 'cluster' };
410
+ } );
411
+ } else {
412
+ singleAssign = assignList.filter( ( item ) => typeof item?.userEmail != 'undefined' && item?.userEmail !='' ).map( ( item ) => {
413
+ return { id: item.assignId, type: 'user' };
414
+ } );
415
+ groupAssign = assignList.filter( ( item ) => typeof item?.teamName != 'undefined' && item?.teamName != '' ).map( ( item ) => {
416
+ return { id: item.assignId, type: 'teams' };
417
+ } );
418
+ }
419
+ result.checkListDetails = { ...result.checkListDetails, ...{ sections: sectionList }, singleAssign, groupAssign };
394
420
  }
395
421
 
396
422
  return res.sendSuccess( result );
@@ -542,7 +568,7 @@ async function createUser( data ) {
542
568
  ],
543
569
  };
544
570
  let response = await userService.create( params );
545
- return response._id;
571
+ return response;
546
572
  } catch ( e ) {
547
573
  logger.error( 'createUser =>', e );
548
574
  return false;
@@ -751,9 +777,13 @@ export const update = async ( req, res ) => {
751
777
  }
752
778
  if ( answer.showLinked ) {
753
779
  if ( nestedIndex != -1 ) {
754
- section.questions[qIdx].answers[nestedIndex].nestedQuestion.push( answer.linkedQuestion );
780
+ if ( !section.questions[qIdx].answers[nestedIndex].nestedQuestion.includes( answer.linkedQuestion ) ) {
781
+ section.questions[qIdx].answers[nestedIndex].nestedQuestion.push( answer.linkedQuestion );
782
+ }
755
783
  } else {
756
- section.questions[qIdx].answers[index].nestedQuestion.push( answer.linkedQuestion );
784
+ if ( !section.questions[qIdx].answers[index].nestedQuestion.includes( answer.linkedQuestion ) ) {
785
+ section.questions[qIdx].answers[index].nestedQuestion.push( answer.linkedQuestion );
786
+ }
757
787
  }
758
788
  let nestedLinkedQuestion = section.questions.find( ( item ) => item.qno == answer.linkedQuestion );
759
789
  if ( nestedLinkedQuestion ) {
@@ -799,6 +829,7 @@ export const update = async ( req, res ) => {
799
829
  }
800
830
  }
801
831
  } ).catch( ( e ) => {
832
+ logger.error( 'update =>', e );
802
833
  return res.sendError( e, 500 );
803
834
  } );
804
835
  } catch ( e ) {
@@ -849,11 +880,11 @@ export const assignedUserDetails = async ( req, res ) => {
849
880
  if ( !req.params.checklistId ) {
850
881
  return res.sendError( { message: 'checklist Id is required' }, 400 );
851
882
  }
852
- let limit = parseInt( req.query.limit ) || 10;
883
+ let limit = parseInt( req.query.limit ) || 5;
853
884
  let page = parseInt( req.query.offset ) || 0;
854
885
  let skip = limit * page;
855
886
 
856
- let query = [ { $match: { checkListId: new ObjectId( req.params.checklistId ) } } ];
887
+ let query = [ { $match: { checkListId: new ObjectId( req.params.checklistId ), ...( req.query.coverage ) ? { coverage: req.query.coverage } : {}, isdeleted: false } } ];
857
888
  if ( req.query.search.trim() && req.query.search.trim() != '' ) {
858
889
  let searchValue = req.query.search;
859
890
  searchValue = searchValue.split( ',' ).map( ( item ) => item.trim().toLowerCase() );
@@ -865,37 +896,176 @@ export const assignedUserDetails = async ( req, res ) => {
865
896
  }
866
897
  }
867
898
 
868
- query.push( {
869
- $facet: {
870
- data: [
871
- { $skip: skip }, { $limit: limit },
872
- ],
873
- count: [
874
- { $count: 'total' },
875
- ],
876
- },
877
- } );
899
+ query.push( { $sort: { _id: -1 } } );
878
900
 
879
901
  let checklistDetails = await assignedService.aggregate( query );
880
-
881
- if ( !checklistDetails[0].data.length ) {
902
+ if ( !checklistDetails.length ) {
882
903
  return res.sendError( 'no data found', 204 );
883
904
  }
884
905
 
885
906
  let userDetails = [];
886
- checklistDetails[0].data.forEach( ( item ) => {
887
- userDetails.push( {
888
- id: item._id,
889
- userName: item.userName,
890
- userEmail: item.userEmail,
891
- store_id: item.store_id,
892
- storeName: item.storeName,
893
- userPhone: item.userPhone,
894
- city: item.city,
895
- checkFlag: item.checkFlag,
907
+ let storeList = [];
908
+ let userList = [];
909
+ await Promise.all( checklistDetails.map( async ( ele ) => {
910
+ if ( ele?.store_id || ele?.clusterName ) {
911
+ storeList.push( ele.assignId );
912
+ } else {
913
+ userList.push( ele.assignId );
914
+ }
915
+
916
+ if ( ele?.clusterName ) {
917
+ let clusterDetails = await clusterServices.findOneCluster( { _id: ele.assignId }, { stores: 1 } );
918
+ if ( clusterDetails ) {
919
+ let storeDetails = await storeService.find( { _id: { $in: clusterDetails.stores.map( ( item ) => item.store ) }, status: 'active' } );
920
+ storeDetails.forEach( ( item ) => {
921
+ userDetails.push( {
922
+ id: ele._id,
923
+ userName: item.spocDetails?.[0]?.name,
924
+ userEmail: item.spocDetails?.[0]?.email,
925
+ store_id: item?.storeId,
926
+ storeName: item?.storeName,
927
+ userPhone: item.spocDetails?.[0]?.phone,
928
+ city: ele?.city,
929
+ checkFlag: ele.checkFlag,
930
+ clusterName: ele?.clusterName || '',
931
+ teamName: ele?.teamName || '',
932
+ } );
933
+ } );
934
+ }
935
+ } else if ( ele?.teamName ) {
936
+ let teamDetails = await teamsServices.findOneTeams( { _id: ele.assignId }, { users: 1, teamName: 1 } );
937
+ if ( teamDetails ) {
938
+ let teamUserDetails = await userService.find( { _id: { $in: teamDetails.users.map( ( item ) => item.userId ) } } );
939
+ teamUserDetails.forEach( ( item ) => {
940
+ userDetails.push( {
941
+ id: ele._id,
942
+ userName: item.userName,
943
+ userEmail: item.email,
944
+ store_id: ele?.storeId,
945
+ storeName: ele?.storeName,
946
+ userPhone: item?.mobileNumber,
947
+ city: ele?.city,
948
+ checkFlag: ele.checkFlag,
949
+ clusterName: ele?.clusterName || '',
950
+ teamName: ele?.teamName || '',
951
+ } );
952
+ } );
953
+ }
954
+ } else {
955
+ userDetails.push( {
956
+ id: ele._id,
957
+ userName: ele.userName,
958
+ userEmail: ele.userEmail,
959
+ store_id: ele?.store_id,
960
+ storeName: ele?.storeName,
961
+ userPhone: ele.userPhone,
962
+ city: ele.city,
963
+ checkFlag: ele.checkFlag,
964
+ clusterName: ele?.clusterName || '',
965
+ teamName: ele?.teamName || '',
966
+ } );
967
+ }
968
+ } ) );
969
+ if ( req.query.sortColumn && req.query.sortBy ) {
970
+ const sortColumn = req.query.sortColumn;
971
+ const sortBy = parseInt( req.query.sortBy, 10 ) === -1 ? -1 : 1;
972
+ userDetails.sort( ( a, b ) => {
973
+ if ( a[sortColumn] == null || b[sortColumn] == null ) return 0;
974
+ if ( typeof a[sortColumn] === 'string' && typeof b[sortColumn] === 'string' ) {
975
+ return sortBy * a[sortColumn].localeCompare( b[sortColumn] );
976
+ }
896
977
  } );
897
- } );
898
- return res.sendSuccess( { users: userDetails, count: checklistDetails[0].count[0].total } );
978
+ }
979
+ let limitedData = userDetails.slice( skip, limit + skip );
980
+ return res.sendSuccess( { count: userDetails.length, storeList, userList, users: limitedData } );
981
+ } catch ( e ) {
982
+ logger.error( 'assignedUserDetails =>', e );
983
+ return res.sendError( e, 500 );
984
+ }
985
+ };
986
+
987
+ export const assignedUserDetailsv1 = async ( req, res ) => {
988
+ try {
989
+ if ( !req.params.checklistId ) {
990
+ return res.sendError( { message: 'checklist Id is required' }, 400 );
991
+ }
992
+ // let limit = parseInt( req.query.limit ) || 5;
993
+ // let page = parseInt( req.query.offset ) || 0;
994
+ // let skip = limit * page;
995
+
996
+ let query = [ { $match: { checkListId: new ObjectId( req.params.checklistId ), isdeleted: false } } ];
997
+
998
+ query.push( { $sort: { _id: -1 } } );
999
+
1000
+ let checklistDetails = await assignedService.aggregate( query );
1001
+ if ( !checklistDetails.length ) {
1002
+ return res.sendError( 'no data found', 204 );
1003
+ }
1004
+
1005
+ let userDetails = [];
1006
+ await Promise.all( checklistDetails.map( async ( ele ) => {
1007
+ if ( ele?.clusterName ) {
1008
+ let clusterDetails = await clusterServices.findOneCluster( { _id: ele.assignId }, { stores: 1 } );
1009
+ if ( clusterDetails ) {
1010
+ let storeDetails = await storeService.find( { _id: { $in: clusterDetails.stores.map( ( item ) => item.store ) }, status: 'active' } );
1011
+ storeDetails.forEach( ( item ) => {
1012
+ userDetails.push( {
1013
+ id: ele.assignId,
1014
+ userName: item.spocDetails?.[0]?.name,
1015
+ userEmail: item.spocDetails?.[0]?.email,
1016
+ storeId: item?.storeId,
1017
+ storeName: item?.storeName,
1018
+ userPhone: item.spocDetails?.[0]?.phone,
1019
+ city: ele?.city,
1020
+ checkFlag: ele.checkFlag,
1021
+ clusterName: ele?.clusterName || '',
1022
+ teamName: ele?.teamName || '',
1023
+ } );
1024
+ } );
1025
+ }
1026
+ } else if ( ele?.teamName ) {
1027
+ let teamDetails = await teamsServices.findOneTeams( { _id: ele.assignId }, { users: 1, teamName: 1, Teamlead: 1 } );
1028
+ if ( teamDetails ) {
1029
+ let idList = [ ...teamDetails.users.map( ( ele ) => ele.userId ), ...teamDetails.Teamlead.map( ( ele ) => ele.userId ) ];
1030
+ let teamUserDetails = await userService.find( { _id: { $in: idList }, isActive: true } );
1031
+ teamUserDetails.forEach( ( item ) => {
1032
+ userDetails.push( {
1033
+ id: ele.assignId,
1034
+ userName: item.userName,
1035
+ userEmail: item.email,
1036
+ storeId: ele?.storeId,
1037
+ storeName: ele?.storeName,
1038
+ userPhone: item?.mobileNumber,
1039
+ city: ele?.city,
1040
+ checkFlag: ele.checkFlag,
1041
+ clusterName: ele?.clusterName || '',
1042
+ teamName: ele?.teamName || '',
1043
+ } );
1044
+ } );
1045
+ }
1046
+ } else {
1047
+ let checkActiveUsers;
1048
+ if ( ele?.coverage == 'user' ) {
1049
+ checkActiveUsers = await userService.findOne( { _id: ele.userId, isActive: true } );
1050
+ }
1051
+ if ( checkActiveUsers || ele?.coverage == 'store' ) {
1052
+ userDetails.push( {
1053
+ _id: ele.assignId,
1054
+ userName: ele.userName,
1055
+ userEmail: ele.userEmail,
1056
+ storeId: ele?.store_id,
1057
+ storeName: ele?.storeName,
1058
+ userPhone: ele.userPhone,
1059
+ city: ele.city,
1060
+ checkFlag: ele.checkFlag,
1061
+ clusterName: ele?.clusterName || '',
1062
+ teamName: ele?.teamName || '',
1063
+ } );
1064
+ }
1065
+ }
1066
+ } ) );
1067
+
1068
+ return res.sendSuccess( { count: userDetails.length, userDetails } );
899
1069
  } catch ( e ) {
900
1070
  logger.error( 'assignedUserDetails =>', e );
901
1071
  return res.sendError( e, 500 );
@@ -1242,187 +1412,401 @@ export const updateConfigure =async ( req, res ) => {
1242
1412
  }
1243
1413
  };
1244
1414
 
1245
- export const updatePublish = async ( req, res ) => {
1415
+ export const updateConfigurev1 =async ( req, res ) => {
1246
1416
  try {
1247
- if ( typeof req?.body?.checklistId == 'undefined' && typeof req.body.type == 'undefined' ) {
1248
- return res.sendError( 'checklistId or type is required', 400 );
1249
- }
1250
-
1251
- if ( typeof req?.body?.publish == 'undefined' ) {
1252
- return res.sendError( 'publish is required', 400 );
1417
+ let inputBody = req.body;
1418
+ let id;
1419
+ let checklistDetails;
1420
+ if ( !inputBody.checkListDetails._id ) {
1421
+ return res.sendError( 'checkListId is Required', 400 );
1253
1422
  }
1254
- let getCheckDetails;
1255
- let query;
1256
1423
 
1257
- if ( req.body.checklistId && typeof req.body.type == 'undefined' ) {
1258
- query = { _id: req.body.checklistId };
1259
- getCheckDetails = await checklistService.findOne( { _id: req.body.checklistId, client_id: req.body.clientId, type: 'checklist' } );
1260
- } else {
1261
- query = { client_id: req.body.clientId, checkListType: req.body.type };
1262
- let findQuery = {};
1263
- if ( req.body.checklistId ) {
1264
- findQuery['_id'] = req.body.checklistId;
1265
- } else {
1266
- findQuery['client_id'] = { $exists: false };
1267
- findQuery['checkListType'] = req.body.type;
1268
- }
1269
- let aiDetails = await checklistService.findOne( findQuery );
1270
- if ( !req.body.checklistId ) {
1271
- getCheckDetails = { ...aiDetails._doc };
1272
- if ( !getCheckDetails.scheduleStartTime ) {
1273
- let brandDetails = await clientService.findOne( { clientId: req.body.clientId } );
1274
- if ( brandDetails ) {
1275
- getCheckDetails.scheduleStartTime = dayjs( brandDetails.featureConfigs.open, 'hh:mm:ss' ).format( 'hh:mm A' );
1276
- getCheckDetails.scheduleEndTime = dayjs( brandDetails.featureConfigs.close, 'hh:mm:ss' ).format( 'hh:mm A' );
1277
- getCheckDetails.scheduleEndTimeISO = dayjs.utc( getCheckDetails.scheduleEndTime, 'hh:mm A' ).format();
1278
- getCheckDetails.scheduleStartTimeISO = dayjs.utc( getCheckDetails.scheduleStartTime, 'hh:mm A' ).format();
1279
- }
1280
- }
1281
- getCheckDetails.schedule = 'daily';
1282
- getCheckDetails.client_id = req.body.clientId;
1283
- getCheckDetails.createdBy = req.user._id;
1284
- getCheckDetails.createdByName = req.user.userName;
1285
- delete getCheckDetails._id;
1286
- } else {
1287
- getCheckDetails = { ...aiDetails._doc };
1424
+ if ( inputBody.checkListDetails.checkListType == 'mobileusagedetection' && inputBody.submitType == 'publish' ) {
1425
+ if ( !inputBody?.checkListDetails?.alert?.usageExceeds ) {
1426
+ return res.sendError( 'Please Enter usage exceeds', 400 );
1288
1427
  }
1289
- }
1290
1428
 
1291
- if ( !getCheckDetails ) {
1292
- return res.sendError( 'no data found', 204 );
1293
- }
1429
+ if ( !inputBody?.checkListDetails?.alert?.alertsTo.length ) {
1430
+ return res.sendError( 'Please select users to send alert', 400 );
1431
+ }
1294
1432
 
1295
- if ( getCheckDetails?.publishDate && getCheckDetails.checkListType == 'custom' ) {
1296
- let date = dayjs();
1297
- let diff = date.diff( dayjs.utc( getCheckDetails?.publishDate ), 'minutes' );
1298
- if ( diff < 5 ) {
1299
- let mins = ( 5 - diff ) > 1 ? 'minutes' : 'minute';
1300
- return res.sendError( `Please try after ${5 - diff} ${mins}`, 400 );
1433
+ if ( !inputBody?.checkListDetails?.detectionArea.length ) {
1434
+ return res.sendError( 'Please select detection area', 400 );
1301
1435
  }
1302
1436
  }
1303
1437
 
1304
- if ( !getCheckDetails.approver.length && req.body.publish && getCheckDetails.checkListType == 'custom' ) {
1305
- return res.sendError( 'Please assign approver', 400 );
1438
+ if ( !inputBody.checkListDetails.assignedUsers.length && inputBody.submitType == 'publish' ) {
1439
+ return res.sendError( 'Please Assigned a user', 400 );
1306
1440
  }
1307
1441
 
1308
- getCheckDetails.publish = req.body.publish;
1309
- getCheckDetails.publishDate = req.body.publish ? new Date() : getCheckDetails?.publishDate;
1310
- let currentDate = dayjs();
1311
- if ( !req.body.publish ) {
1312
- await processedchecklistConfig.deleteMany( { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId } );
1313
- await processedchecklist.deleteMany( { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId, checklistStatus: { $ne: 'submit' } } );
1314
- logger.info( { function: 'updatePublish', query: { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId, checklistStatus: { $ne: 'submit' } } } );
1442
+ if ( !inputBody?.checkListDetails?.approver.length && inputBody.submitType == 'publish' ) {
1443
+ return res.sendError( 'Please assign approver', 400 );
1315
1444
  }
1316
1445
 
1317
1446
 
1318
- await checklistService.updateOne( query, getCheckDetails );
1319
- if ( getCheckDetails.checkListType == 'custom' ) {
1320
- let currentDate = dayjs.utc().format();
1321
- let updatedscheduleEndTimeISO = dayjs.utc( getCheckDetails.scheduleEndTimeISO ).format( 'HH:mm:ss' );
1322
- let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1323
-
1324
- if ( req.body.publish && req.body.publish == true ) {
1325
- if ( newUpdatedDate > currentDate ) {
1326
- let deleteQuery = {
1327
- $and: [
1328
- { date_string: dayjs().format( 'YYYY-MM-DD' ) },
1329
- { sourceCheckList_id: new ObjectId( req.body.checklistId ) },
1330
- { scheduleEndTime_iso: { $gt: currentDate } },
1331
- ],
1332
- };
1333
- deleteQuery.$and.push( { checklistStatus: { $eq: 'open' } } );
1334
- let PClicklist = await processedchecklist.deleteMany( deleteQuery );
1335
- logger.info( { function: 'updatePublish', query: deleteQuery } );
1336
- logger.info( `Deleted Checklist Before Insert => Checklist Name: ${getCheckDetails.checkListName}, PChecklist Count: ${PClicklist.deletedCount}` );
1337
- if ( PClicklist.acknowledged ) {
1338
- await insertSingleProcessData( req.body.checklistId );
1339
- } else {
1340
- res.sendError( 'something went wrong, please try again', 500 );
1341
- }
1342
- } else {
1343
- logger.info( `Schudled End Time Breached Checklist publish true => Checklist Name: ${getCheckDetails.checkListName}` );
1344
- }
1345
-
1346
- futureDaysDataRemove( currentDate, req.body.checklistId, getCheckDetails.checkListName, '111' );
1347
- } else {
1348
- if ( newUpdatedDate > currentDate ) {
1349
- let deleteQuery = {
1350
- $and: [
1351
- { date_string: dayjs().format( 'YYYY-MM-DD' ) },
1352
- { sourceCheckList_id: new ObjectId( req.body.checklistId ) },
1353
- { scheduleEndTime_iso: { $gt: currentDate } },
1354
- ],
1355
- };
1356
- // await processedchecklistConfig.deleteMany( deleteQuery );
1357
- deleteQuery.$and.push( { checklistStatus: { $eq: 'open' } } );
1358
- await processedchecklist.deleteMany( deleteQuery );
1359
- logger.info( { function: 'updatePublish', query: deleteQuery } );
1360
-
1361
- let checklistLogQuery = {};
1362
- checklistLogQuery.checkListName = getCheckDetails.checkListName;
1363
- checklistLogQuery.createdAt = { $gte: new Date( dayjs().format( 'YYYY-MM-DD' ) ) };
1364
- await checklistLogs.deleteMany( checklistLogQuery );
1365
-
1366
- let checklistDetectionsQuery = {};
1367
- checklistDetectionsQuery.sourceChecklist_id = new ObjectId( req.body.checklistId );
1368
- checklistDetectionsQuery.date_iso = { $gte: new Date( dayjs().format( 'YYYY-MM-DD' ) ) };
1369
- // await processeddetections.deleteMany( checklistDetectionsQuery );
1370
- logger.info( { function: 'updatePublish', query: checklistDetectionsQuery } );
1371
- } else {
1372
- logger.info( `Schudled End Time Breached Checklist Unpublish false => Checklist Name: ${getCheckDetails.checkListName}` );
1373
- }
1374
-
1375
- // //Delete Future Data////
1376
- futureDaysDataRemove( currentDate, req.body.checklistId, getCheckDetails.checkListName, '222' );
1377
- }
1378
- }
1379
1447
  let logInsertData = {
1380
- action: req.body.publish ? 'publishChecklist' : 'unPublishChecklist',
1381
- ...( req.body?.checklistId ) ? { checklistId: req.body?.checklistId } : { type: req.body?.type },
1382
- checkListName: getCheckDetails.checkListName,
1448
+ action: inputBody.submitType == 'publish' ? 'checklistPublishUsingConfigPage' : 'checklistConfigDraft',
1449
+ checklistId: inputBody.checkListDetails._id,
1450
+ checkListName: inputBody?.checkListDetails.checkListName,
1383
1451
  createdBy: req.user._id,
1384
1452
  createdByName: req.user.userName,
1385
1453
  client_id: req.body.clientId,
1386
1454
  createdByEmail: req.user.email,
1455
+ approver: inputBody?.checkListDetails?.approver || [],
1387
1456
  };
1388
1457
  await checklistLogs.create( logInsertData );
1389
- return res.sendSuccess( { checklistName: getCheckDetails.checkListName, message: 'Updated Successfully' } );
1390
- } catch ( e ) {
1391
- logger.error( 'updatePublish erroe =>', e );
1392
- return res.sendError( e, 500 );
1393
- }
1394
- };
1395
1458
 
1396
- async function futureDaysDataRemove( currentDate, checklistId, checkListName, sourcefrom ) {
1397
- // //Delete Future Datas////
1398
- let futureDataDeleteQuery = {
1399
- $and: [
1400
- { date_iso: { $gt: currentDate } },
1401
- { sourceCheckList_id: new ObjectId( checklistId ) },
1402
- ],
1403
- };
1404
- await processedchecklistConfig.deleteMany( futureDataDeleteQuery );
1405
- futureDataDeleteQuery.$and.push( { checklistStatus: { $ne: 'submit' } } );
1406
- await processedchecklist.deleteMany( futureDataDeleteQuery );
1407
- logger.info( { function: 'futureDaysDataRemove', query: futureDataDeleteQuery } );
1408
- // ///////////////////////////////
1409
- return true;
1410
- }
1459
+ checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist', isdeleted: false } );
1411
1460
 
1412
- export const validateUser = async ( req, res ) => {
1413
- try {
1414
- if ( !req.body.assignedUsers.length ) {
1415
- return res.sendError( 'Please Enter user Details', 400 );
1461
+ if ( [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection' ].includes( inputBody.checkListDetails.checkListType ) && inputBody.uploadUser ) {
1462
+ checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist' } );
1416
1463
  }
1417
1464
 
1418
- let users = req.body.assignedUsers;
1419
- let userEmail = [];
1420
- let storeId = [];
1421
- let domainExists = [];
1465
+ if ( !checklistDetails ) {
1466
+ return res.sendError( 'no data found', 204 );
1467
+ }
1468
+ let currentDate;
1469
+ if ( inputBody.timeZone ) {
1470
+ currentDate = dayjs().tz( inputBody.timeZone ).format();
1471
+ } else {
1472
+ currentDate = dayjs().format( 'HH:mm:ss' );
1473
+ }
1474
+ currentDate = dayjs.utc( currentDate, 'HH:mm:ss' ).format();
1475
+ let updatedscheduleEndTimeISO = dayjs.utc( inputBody?.checkListDetails?.scheduleEndTime, 'hh:mm A' ).format( 'HH:mm:ss' );
1476
+ let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1422
1477
 
1423
- const duplicateStore = users.reduce( ( acc, obj ) => {
1424
- if ( !acc[obj.storeName.toLowerCase()] ) {
1425
- acc[obj.storeName.toLowerCase()] = {
1478
+ if ( inputBody.submitType == 'publish' && inputBody?.showEdit && typeof inputBody?.editSubmit == 'undefined' && newUpdatedDate > currentDate ) {
1479
+ let checkSubmitDetails = await processedchecklist.findOne( { sourceCheckList_id: inputBody.checkListDetails._id, date_string: dayjs().format( 'YYYY-MM-DD' ), checklistStatus: 'submit' } );
1480
+ if ( checkSubmitDetails ) {
1481
+ return res.sendError( 'Checklist got submitted', 400 );
1482
+ }
1483
+ }
1484
+
1485
+ if ( checklistDetails?.publishDate && inputBody.submitType == 'publish' ) {
1486
+ let date = dayjs();
1487
+ let diff = date.diff( dayjs.utc( checklistDetails?.publishDate ), 'minutes' );
1488
+ if ( diff < 5 ) {
1489
+ let mins = ( 5 - diff ) > 1 ? 'minutes' : 'minute';
1490
+ return res.sendError( `Please try after ${5 - diff} ${mins}`, 400 );
1491
+ }
1492
+ }
1493
+
1494
+ if ( inputBody?.checkListDetails?.scheduleRepeatedMonthSetup == 'date' ) {
1495
+ inputBody.checkListDetails.scheduleRepeatedDay = inputBody?.checkListDetails?.scheduleRepeatedDay;
1496
+ }
1497
+
1498
+ if ( inputBody?.checkListDetails?.scheduleDate ) {
1499
+ inputBody.checkListDetails.scheduleDate = new Date( inputBody?.checkListDetails?.scheduleDate );
1500
+ }
1501
+ let configDetails = {
1502
+ ...inputBody?.checkListDetails,
1503
+ publishDate: inputBody.checkListDetails.publish ? new Date() : '',
1504
+ scheduleRepeatedType: inputBody?.checkListDetails?.schedule,
1505
+ scheduleStartTimeISO: dayjs.utc( inputBody?.checkListDetails?.scheduleStartTime, 'hh:mm A' ).format(),
1506
+ scheduleEndTimeISO: dayjs.utc( inputBody?.checkListDetails?.scheduleEndTime, 'hh:mm A' ).format(),
1507
+ scheduleDate: inputBody?.checkListDetails?.scheduleDate ? dayjs( inputBody.checkListDetails.scheduleDate ).format() : '',
1508
+ approver: inputBody?.checkListDetails?.approver.length ? inputBody?.checkListDetails?.approver.map( ( item ) => {
1509
+ return { name: item.name, value: item.value };
1510
+ } ) : [],
1511
+ };
1512
+
1513
+ if ( inputBody?.checkListDetails?.approver.length ) {
1514
+ let data = [];
1515
+ let existEmail = await traxApprover.find( { checkListId: inputBody.checkListDetails._id, isDeleted: false } );
1516
+ let mailList = existEmail.map( ( item ) => item.userEmail );
1517
+ existEmail = inputBody?.checkListDetails?.approver.filter( ( item ) => mailList.includes( item.value ) ).map( ( item ) => item.value );
1518
+ let userMailList = inputBody?.checkListDetails?.approver.map( ( ele ) => ele.value );
1519
+ inputBody?.checkListDetails?.approver.forEach( ( ele ) => {
1520
+ if ( !existEmail.includes( ele.value ) ) {
1521
+ data.push( {
1522
+ userEmail: ele.value,
1523
+ checkListId: inputBody.checkListDetails._id,
1524
+ type: 'checklist',
1525
+ checkListName: inputBody?.checkListDetails.checkListName,
1526
+ client_id: inputBody?.clientId,
1527
+ } );
1528
+ }
1529
+ } );
1530
+
1531
+ await traxApprover.updateMany( { checkListId: inputBody.checkListDetails._id, userEmail: { $nin: userMailList } }, { isDeleted: true } );
1532
+ if ( data.length ) {
1533
+ await traxApprover.insertMany( data );
1534
+ }
1535
+ }
1536
+
1537
+ if ( checklistDetails.checkListType != 'custom' && !checklistDetails.client_id ) {
1538
+ let getchecklistNumber = await checklistService.findOne( { client_id: req.body.clientId, type: 'checklist' }, { checkListNumber: 1 } );
1539
+ let name = checklistDetails.checkListName.split( '(' )[0];
1540
+ let checkListNameDetails = await checklistService.find( { checkListName: { $regex: name }, client_id: req.body.clientId, type: 'checklist', isdeleted: false } );
1541
+ if ( checkListNameDetails.length ) {
1542
+ let nameLength = ( checkListNameDetails.length-1 ) + 1;
1543
+ checklistDetails.checkListName = checklistDetails.checkListName.split( '(' )[0] + '(' + nameLength + ')';
1544
+ } else {
1545
+ checklistDetails.checkListName = checklistDetails.checkListName;
1546
+ }
1547
+ configDetails.type = 'checklist';
1548
+ configDetails.checkListName = checklistDetails.checkListName;
1549
+ configDetails.checkListDescription = checklistDetails.checkListDescription;
1550
+ if ( getchecklistNumber ) {
1551
+ configDetails.checkListNumber = getchecklistNumber.checkListNumber + 1;
1552
+ } else {
1553
+ configDetails.checkListNumber = 1;
1554
+ }
1555
+ configDetails.createdBy= req.user._id;
1556
+ configDetails.createdByName=req.user.userName;
1557
+ delete inputBody.checkListDetails['_id'];
1558
+ if ( [ 'storeopenandclose', 'uniformdetection' ].includes( checklistDetails.checkListType ) ) {
1559
+ let query = { client_id: req.body.clientId, type: 'checklist', isdeleted: false };
1560
+ if ( checklistDetails.checkListType == 'storeopenandclose' ) {
1561
+ query.checkListType= 'storeopenandclose';
1562
+ } else {
1563
+ query.checkListType= 'uniformdetection';
1564
+ }
1565
+ let storeChecklisDetails = await checklistService.findOne( query );
1566
+ if ( storeChecklisDetails ) {
1567
+ inputBody.checkListDetails._id = storeChecklisDetails._id;
1568
+ }
1569
+ }
1570
+ }
1571
+ let query = {
1572
+ client_id: req.body.clientId,
1573
+ checkListType: checklistDetails.checkListType,
1574
+ _id: inputBody.checkListDetails._id,
1575
+ };
1576
+ let response;
1577
+ if ( inputBody.checkListDetails._id ) {
1578
+ if ( [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection' ].includes( inputBody.checkListDetails.checkListType ) && inputBody.uploadUser ) {
1579
+ configDetails.isdeleted = false;
1580
+ }
1581
+ id = inputBody.checkListDetails._id;
1582
+ response = await checklistService.updateOne( query, configDetails );
1583
+ } else {
1584
+ configDetails.client_id = req.body.clientId;
1585
+ configDetails.checkListType = checklistDetails.checkListType;
1586
+ response = await checklistService.create( configDetails );
1587
+ id = response._id;
1588
+ }
1589
+ if ( inputBody.submitType == 'publish' ) {
1590
+ if ( inputBody.checkListDetails.checkListType == 'custom' ) {
1591
+ let currentDate = dayjs.utc().format();
1592
+ let updatedscheduleEndTimeISO = dayjs.utc( configDetails.scheduleEndTimeISO ).format( 'HH:mm:ss' );
1593
+ let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1594
+ if ( newUpdatedDate > currentDate ) {
1595
+ let deleteQuery = {
1596
+ $and: [
1597
+ { date_string: dayjs().format( 'YYYY-MM-DD' ) },
1598
+ { sourceCheckList_id: new ObjectId( req.params.checklistId ) },
1599
+ { scheduleEndTime_iso: { $gt: currentDate } },
1600
+ ],
1601
+ };
1602
+ deleteQuery.$and.push( { checklistStatus: { $ne: 'submit' } } );
1603
+ let PClicklist = await processedchecklist.deleteMany( deleteQuery );
1604
+ logger.info( { function: 'updateConfigure', query: deleteQuery } );
1605
+ if ( PClicklist.acknowledged || inputBody.updateConfigure ) {
1606
+ await insertSingleProcessData( inputBody.checkListDetails._id, 0, inputBody.updateConfigure, inputBody?.editSubmit, inputBody?.showEdit );
1607
+ } else {
1608
+ res.sendError( 'something went wrong, please try again', 500 );
1609
+ }
1610
+ } else {
1611
+ logger.info( `Schudled End Time Breached Checklist publish true => Checklist Name: ${checklistDetails.checkListName}` );
1612
+ }
1613
+
1614
+ futureDaysDataRemove( currentDate, req.params.checklistId, checklistDetails.checkListName, '333' );
1615
+ }
1616
+ }
1617
+ if ( response?.modifiedCount || response?.matchedCount || response?.upsertedCount ) {
1618
+ return res.sendSuccess( { id, message: 'Configured Updated Successfully' } );
1619
+ }
1620
+ if ( response._id ) {
1621
+ return res.sendSuccess( { id, message: 'Configured Added Successfully' } );
1622
+ }
1623
+ } catch ( e ) {
1624
+ logger.error( 'updateConfigure =>', e );
1625
+ return res.sendError( e, 500 );
1626
+ }
1627
+ };
1628
+
1629
+ export const updatePublish = async ( req, res ) => {
1630
+ try {
1631
+ if ( typeof req?.body?.checklistId == 'undefined' && typeof req.body.type == 'undefined' ) {
1632
+ return res.sendError( 'checklistId or type is required', 400 );
1633
+ }
1634
+
1635
+ if ( typeof req?.body?.publish == 'undefined' ) {
1636
+ return res.sendError( 'publish is required', 400 );
1637
+ }
1638
+ let getCheckDetails;
1639
+ let query;
1640
+
1641
+ if ( req.body.checklistId && typeof req.body.type == 'undefined' ) {
1642
+ query = { _id: req.body.checklistId };
1643
+ getCheckDetails = await checklistService.findOne( { _id: req.body.checklistId, client_id: req.body.clientId, type: 'checklist' } );
1644
+ } else {
1645
+ query = { client_id: req.body.clientId, checkListType: req.body.type };
1646
+ let findQuery = {};
1647
+ if ( req.body.checklistId ) {
1648
+ findQuery['_id'] = req.body.checklistId;
1649
+ } else {
1650
+ findQuery['client_id'] = { $exists: false };
1651
+ findQuery['checkListType'] = req.body.type;
1652
+ }
1653
+ let aiDetails = await checklistService.findOne( findQuery );
1654
+ if ( !req.body.checklistId ) {
1655
+ getCheckDetails = { ...aiDetails._doc };
1656
+ if ( !getCheckDetails.scheduleStartTime ) {
1657
+ let brandDetails = await clientService.findOne( { clientId: req.body.clientId } );
1658
+ if ( brandDetails ) {
1659
+ getCheckDetails.scheduleStartTime = dayjs( brandDetails.featureConfigs.open, 'hh:mm:ss' ).format( 'hh:mm A' );
1660
+ getCheckDetails.scheduleEndTime = dayjs( brandDetails.featureConfigs.close, 'hh:mm:ss' ).format( 'hh:mm A' );
1661
+ getCheckDetails.scheduleEndTimeISO = dayjs.utc( getCheckDetails.scheduleEndTime, 'hh:mm A' ).format();
1662
+ getCheckDetails.scheduleStartTimeISO = dayjs.utc( getCheckDetails.scheduleStartTime, 'hh:mm A' ).format();
1663
+ }
1664
+ }
1665
+ getCheckDetails.schedule = 'daily';
1666
+ getCheckDetails.client_id = req.body.clientId;
1667
+ getCheckDetails.createdBy = req.user._id;
1668
+ getCheckDetails.createdByName = req.user.userName;
1669
+ delete getCheckDetails._id;
1670
+ } else {
1671
+ getCheckDetails = { ...aiDetails._doc };
1672
+ }
1673
+ }
1674
+
1675
+ if ( !getCheckDetails ) {
1676
+ return res.sendError( 'no data found', 204 );
1677
+ }
1678
+
1679
+ if ( getCheckDetails?.publishDate && getCheckDetails.checkListType == 'custom' ) {
1680
+ let date = dayjs();
1681
+ let diff = date.diff( dayjs.utc( getCheckDetails?.publishDate ), 'minutes' );
1682
+ if ( diff < 5 ) {
1683
+ let mins = ( 5 - diff ) > 1 ? 'minutes' : 'minute';
1684
+ return res.sendError( `Please try after ${5 - diff} ${mins}`, 400 );
1685
+ }
1686
+ }
1687
+
1688
+ if ( !getCheckDetails.approver.length && req.body.publish && getCheckDetails.checkListType == 'custom' ) {
1689
+ return res.sendError( 'Please assign approver', 400 );
1690
+ }
1691
+
1692
+ getCheckDetails.publish = req.body.publish;
1693
+ getCheckDetails.publishDate = req.body.publish ? new Date() : getCheckDetails?.publishDate;
1694
+ let currentDate = dayjs();
1695
+ if ( !req.body.publish ) {
1696
+ await processedchecklistConfig.deleteMany( { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId } );
1697
+ await processedchecklist.deleteMany( { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId, checklistStatus: { $ne: 'submit' } } );
1698
+ logger.info( { function: 'updatePublish', query: { date_string: { $gt: currentDate.format( 'YYYY-MM-DD' ) }, date_iso: { $gt: currentDate.format( '' ) }, sourceCheckList_id: req.body.checklistId, checklistStatus: { $ne: 'submit' } } } );
1699
+ }
1700
+
1701
+
1702
+ await checklistService.updateOne( query, getCheckDetails );
1703
+ if ( getCheckDetails.checkListType == 'custom' ) {
1704
+ let currentDate = dayjs.utc().format();
1705
+ let updatedscheduleEndTimeISO = dayjs.utc( getCheckDetails.scheduleEndTimeISO ).format( 'HH:mm:ss' );
1706
+ let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1707
+
1708
+ if ( req.body.publish && req.body.publish == true ) {
1709
+ if ( newUpdatedDate > currentDate ) {
1710
+ let deleteQuery = {
1711
+ $and: [
1712
+ { date_string: dayjs().format( 'YYYY-MM-DD' ) },
1713
+ { sourceCheckList_id: new ObjectId( req.body.checklistId ) },
1714
+ { scheduleEndTime_iso: { $gt: currentDate } },
1715
+ ],
1716
+ };
1717
+ deleteQuery.$and.push( { checklistStatus: { $eq: 'open' } } );
1718
+ let PClicklist = await processedchecklist.deleteMany( deleteQuery );
1719
+ logger.info( { function: 'updatePublish', query: deleteQuery } );
1720
+ logger.info( `Deleted Checklist Before Insert => Checklist Name: ${getCheckDetails.checkListName}, PChecklist Count: ${PClicklist.deletedCount}` );
1721
+ if ( PClicklist.acknowledged ) {
1722
+ await insertSingleProcessData( req.body.checklistId );
1723
+ } else {
1724
+ res.sendError( 'something went wrong, please try again', 500 );
1725
+ }
1726
+ } else {
1727
+ logger.info( `Schudled End Time Breached Checklist publish true => Checklist Name: ${getCheckDetails.checkListName}` );
1728
+ }
1729
+
1730
+ futureDaysDataRemove( currentDate, req.body.checklistId, getCheckDetails.checkListName, '111' );
1731
+ } else {
1732
+ if ( newUpdatedDate > currentDate ) {
1733
+ let deleteQuery = {
1734
+ $and: [
1735
+ { date_string: dayjs().format( 'YYYY-MM-DD' ) },
1736
+ { sourceCheckList_id: new ObjectId( req.body.checklistId ) },
1737
+ { scheduleEndTime_iso: { $gt: currentDate } },
1738
+ ],
1739
+ };
1740
+ // await processedchecklistConfig.deleteMany( deleteQuery );
1741
+ deleteQuery.$and.push( { checklistStatus: { $eq: 'open' } } );
1742
+ await processedchecklist.deleteMany( deleteQuery );
1743
+ logger.info( { function: 'updatePublish', query: deleteQuery } );
1744
+
1745
+ let checklistLogQuery = {};
1746
+ checklistLogQuery.checkListName = getCheckDetails.checkListName;
1747
+ checklistLogQuery.createdAt = { $gte: new Date( dayjs().format( 'YYYY-MM-DD' ) ) };
1748
+ await checklistLogs.deleteMany( checklistLogQuery );
1749
+
1750
+ let checklistDetectionsQuery = {};
1751
+ checklistDetectionsQuery.sourceChecklist_id = new ObjectId( req.body.checklistId );
1752
+ checklistDetectionsQuery.date_iso = { $gte: new Date( dayjs().format( 'YYYY-MM-DD' ) ) };
1753
+ // await processeddetections.deleteMany( checklistDetectionsQuery );
1754
+ logger.info( { function: 'updatePublish', query: checklistDetectionsQuery } );
1755
+ } else {
1756
+ logger.info( `Schudled End Time Breached Checklist Unpublish false => Checklist Name: ${getCheckDetails.checkListName}` );
1757
+ }
1758
+
1759
+ // //Delete Future Data////
1760
+ futureDaysDataRemove( currentDate, req.body.checklistId, getCheckDetails.checkListName, '222' );
1761
+ }
1762
+ }
1763
+ let logInsertData = {
1764
+ action: req.body.publish ? 'publishChecklist' : 'unPublishChecklist',
1765
+ ...( req.body?.checklistId ) ? { checklistId: req.body?.checklistId } : { type: req.body?.type },
1766
+ checkListName: getCheckDetails.checkListName,
1767
+ createdBy: req.user._id,
1768
+ createdByName: req.user.userName,
1769
+ client_id: req.body.clientId,
1770
+ createdByEmail: req.user.email,
1771
+ };
1772
+ await checklistLogs.create( logInsertData );
1773
+ return res.sendSuccess( { checklistName: getCheckDetails.checkListName, message: 'Updated Successfully' } );
1774
+ } catch ( e ) {
1775
+ logger.error( 'updatePublish erroe =>', e );
1776
+ return res.sendError( e, 500 );
1777
+ }
1778
+ };
1779
+
1780
+ async function futureDaysDataRemove( currentDate, checklistId, checkListName, sourcefrom ) {
1781
+ // //Delete Future Datas////
1782
+ let futureDataDeleteQuery = {
1783
+ $and: [
1784
+ { date_iso: { $gt: currentDate } },
1785
+ { sourceCheckList_id: new ObjectId( checklistId ) },
1786
+ ],
1787
+ };
1788
+ await processedchecklistConfig.deleteMany( futureDataDeleteQuery );
1789
+ futureDataDeleteQuery.$and.push( { checklistStatus: { $ne: 'submit' } } );
1790
+ await processedchecklist.deleteMany( futureDataDeleteQuery );
1791
+ logger.info( { function: 'futureDaysDataRemove', query: futureDataDeleteQuery } );
1792
+ // ///////////////////////////////
1793
+ return true;
1794
+ }
1795
+
1796
+ export const validateUser = async ( req, res ) => {
1797
+ try {
1798
+ if ( !req.body.assignedUsers.length ) {
1799
+ return res.sendError( 'Please Enter user Details', 400 );
1800
+ }
1801
+
1802
+ let users = req.body.assignedUsers;
1803
+ let userEmail = [];
1804
+ let storeId = [];
1805
+ let domainExists = [];
1806
+
1807
+ const duplicateStore = users.reduce( ( acc, obj ) => {
1808
+ if ( !acc[obj.storeName.toLowerCase()] ) {
1809
+ acc[obj.storeName.toLowerCase()] = {
1426
1810
  email: [ obj.userEmail.toLowerCase() ],
1427
1811
  count: 1,
1428
1812
  };
@@ -1552,24 +1936,255 @@ export const validateUser = async ( req, res ) => {
1552
1936
  } ) );
1553
1937
  }
1554
1938
  } else {
1555
- if ( req.body.hasOwnProperty( 'delete' ) ) {
1556
- let checkExists = await assignedService.findOne( { userEmail: req.body.assignedUsers[0].userEmail, storeName: req.body.assignedUsers[0].storeName, checkListId: req.body.id } );
1557
- if ( checkExists ) {
1558
- return res.sendError( 'User already Exists', 400 );
1939
+ if ( req.body.hasOwnProperty( 'delete' ) ) {
1940
+ let checkExists = await assignedService.findOne( { userEmail: req.body.assignedUsers[0].userEmail, storeName: req.body.assignedUsers[0].storeName, checkListId: req.body.id } );
1941
+ if ( checkExists ) {
1942
+ return res.sendError( 'User already Exists', 400 );
1943
+ }
1944
+ }
1945
+
1946
+ let id = await uploadUser( req, res );
1947
+ if ( id ) {
1948
+ return res.sendSuccess( { validate: true, id } );
1949
+ }
1950
+ }
1951
+ } catch ( e ) {
1952
+ logger.error( 'validateUser 2=>', e );
1953
+ return res.sendError( e, 500 );
1954
+ }
1955
+ };
1956
+
1957
+ export const validateUserv1 = async ( req, res ) => {
1958
+ try {
1959
+ if ( !req.body.assignedUsers?.length ) {
1960
+ return res.sendError( 'Please Enter user Details', 400 );
1961
+ }
1962
+
1963
+ let assignDetails = req.body.assignedUsers;
1964
+
1965
+ if ( req.body.coverage == 'store' ) {
1966
+ const duplicateStore = assignDetails.reduce( ( acc, obj ) => {
1967
+ if ( !acc[obj.storeName.toLowerCase()] ) {
1968
+ acc[obj.storeName.toLowerCase()] = {
1969
+ email: [ obj.userEmail.toLowerCase() ],
1970
+ count: 1,
1971
+ };
1972
+ } else {
1973
+ if ( acc[obj.storeName.toLowerCase()] ) {
1974
+ if ( acc[obj.storeName.toLowerCase()].email.includes( obj.userEmail.toLowerCase() ) ) {
1975
+ acc[obj.storeName.toLowerCase()].count++;
1976
+ } else {
1977
+ acc[obj.storeName.toLowerCase()].email.push( obj.userEmail.toLowerCase() );
1978
+ }
1979
+ }
1980
+ }
1981
+ return acc;
1982
+ }, {} );
1983
+
1984
+ const duplicateStores = Object.keys( duplicateStore ).filter( ( storeName ) => duplicateStore[storeName].count > 1 );
1985
+ if ( duplicateStores.length ) {
1986
+ return res.sendError( { validate: false, duplicates: duplicateStores, message: 'Store and email is duplicated' }, 400 );
1987
+ }
1988
+ } else {
1989
+ const duplicateUser = assignDetails.reduce( ( acc, obj ) => {
1990
+ if ( !acc[obj.userEmail.toLowerCase()] ) {
1991
+ acc[obj.userEmail.toLowerCase()] = {
1992
+ name: [ obj.userName.toLowerCase() ],
1993
+ count: 1,
1994
+ };
1995
+ } else {
1996
+ if ( acc[obj.userEmail.toLowerCase()] ) {
1997
+ acc[obj.userEmail.toLowerCase()].name.push( obj.userName.toLowerCase() );
1998
+ acc[obj.userEmail.toLowerCase()].count++;
1999
+ }
2000
+ }
2001
+ return acc;
2002
+ }, {} );
2003
+
2004
+ const duplicateUsers = Object.keys( duplicateUser ).filter( ( storeName ) => duplicateUser[storeName].count > 1 );
2005
+ console.log( duplicateUsers, 'user' );
2006
+ if ( duplicateUsers.length ) {
2007
+ return res.sendError( { validate: false, duplicates: duplicateUsers, message: 'Email is Duplicated' }, 400 );
2008
+ }
2009
+ }
2010
+
2011
+ if ( req.body.hasOwnProperty( 'addSingle' ) ) {
2012
+ let checkExists = await assignedService.findOne( { userEmail: assignDetails[0]?.userEmail, storeName: assignDetails[0]?.storeName, checkListId: req.body.id } );
2013
+ if ( checkExists ) {
2014
+ return res.sendError( 'User already Exists', 400 );
2015
+ }
2016
+ }
2017
+
2018
+ let userEmailList = assignDetails.map( ( item ) => item?.userEmail?.trim()?.toLowerCase() );
2019
+ let storeList = assignDetails.map( ( item ) => item?.storeName?.trim()?.toLowerCase() );
2020
+
2021
+ let userQuery = [
2022
+ {
2023
+ $project: {
2024
+ newEmail: { $toLower: '$email' },
2025
+ isActive: 1,
2026
+ clientId: 1,
2027
+ userName: 1,
2028
+ email: 1,
2029
+ },
2030
+ },
2031
+ {
2032
+ $match: {
2033
+ newEmail: { $in: userEmailList },
2034
+ isActive: true,
2035
+ clientId: req.body.clientId,
2036
+ },
2037
+ },
2038
+ ];
2039
+
2040
+ let emailCheckQuery = [
2041
+ {
2042
+ $project: {
2043
+ newEmail: { $toLower: '$email' },
2044
+ // isActive: 1,
2045
+ clientId: 1,
2046
+ email: 1,
2047
+ },
2048
+ },
2049
+ {
2050
+ $match: {
2051
+ newEmail: { $in: userEmailList },
2052
+ // isActive: true,
2053
+ clientId: { $ne: req.body.clientId },
2054
+ },
2055
+ },
2056
+ ];
2057
+
2058
+ let storeQuery = [
2059
+ {
2060
+ $project: {
2061
+ 'store': { $toLower: '$storeName' },
2062
+ 'clientId': 1,
2063
+ 'storeProfile.city': 1,
2064
+ 'status': 1,
2065
+ 'storeId': 1,
2066
+ 'spocDetails': 1,
2067
+ 'storeName': 1,
2068
+ },
2069
+ },
2070
+ {
2071
+ $match: {
2072
+ clientId: req.body.clientId,
2073
+ store: { $in: storeList },
2074
+ },
2075
+ },
2076
+ ];
2077
+
2078
+ let [ userDetails, storeDetails, existEmail ] = await Promise.all( [
2079
+ await userService.aggregate( userQuery ),
2080
+ await storeService.aggregate( storeQuery ),
2081
+ await userService.aggregate( emailCheckQuery ),
2082
+ ] );
2083
+
2084
+
2085
+ existEmail = existEmail.map( ( ele ) => ele.newEmail );
2086
+ let existUserEmail = userDetails.map( ( ele ) => ele.newEmail );
2087
+ let newUserList = userEmailList.filter( ( ele ) => !existUserEmail.includes( ele ) && !existEmail.includes( ele ) );
2088
+ let inActiveStores = storeDetails.filter( ( ele ) => ele.status == 'deactive' ).map( ( ele ) => ele.storeName );
2089
+
2090
+ let existsStore = storeDetails.map( ( ele ) => ele.storeName.toLowerCase() );
2091
+ let newStoreList = storeList.filter( ( ele ) => ele != null && !existsStore.includes( ele.toLowerCase() ) );
2092
+ if ( req.body.coverage == 'store' ) {
2093
+ assignDetails.forEach( ( item ) => {
2094
+ let getStoreDetails = storeDetails.find( ( store ) => store.storeName.trim().toLowerCase() == item.storeName.trim().toLowerCase() );
2095
+ if ( getStoreDetails ) {
2096
+ let storeUserDetails = userDetails.find( ( ele ) => ele.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
2097
+ item._id = getStoreDetails._id;
2098
+ item.storeId = getStoreDetails.storeId;
2099
+ item.userName = getStoreDetails?.spocDetails?.[0]?.email.toLowerCase() == item.userEmail.toLowerCase() ? getStoreDetails?.spocDetails?.[0]?.name : storeUserDetails?.email == item.userEmail.toLowerCase() ? storeUserDetails?.userName : item.userName;
2100
+ item.storeName = getStoreDetails.storeName;
2101
+ item.userEmail = storeUserDetails?.email || item.userEmail;
2102
+ }
2103
+ } );
2104
+ } else {
2105
+ assignDetails.forEach( ( item ) => {
2106
+ let getUserDetails = userDetails.find( ( user ) => user.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
2107
+ if ( getUserDetails ) {
2108
+ item._id = getUserDetails._id;
2109
+ item.userName = getUserDetails.userName;
2110
+ item.userEmail = getUserDetails.email;
1559
2111
  }
1560
- }
2112
+ } );
2113
+ }
1561
2114
 
1562
- let id = await uploadUser( req, res );
1563
- if ( id ) {
1564
- return res.sendSuccess( { validate: true, id } );
2115
+ if ( ( newUserList.length || newStoreList.length || existEmail.length || inActiveStores.length ) && !req.body?.addUser ) {
2116
+ newStoreList = [ ...new Set( newStoreList.map( ( item ) => item ) ) ];
2117
+ newUserList = [ ...new Set( newUserList.map( ( item ) => item ) ) ];
2118
+ existEmail = [ ...new Set( existEmail.map( ( item ) => item ) ) ];
2119
+ inActiveStores = [ ...new Set( inActiveStores.map( ( item ) => item ) ) ];
2120
+ return res.sendError( { validate: false, user: newUserList, store: newStoreList, existEmail, inActiveStores, data: assignDetails }, 400 );
2121
+ }
2122
+ await Promise.all( newUserList.map( async ( ele ) => {
2123
+ let findUserIndex = assignDetails.findIndex( ( item ) => item?.userEmail?.toLowerCase() == ele?.toLowerCase() );
2124
+ if ( findUserIndex != -1 ) {
2125
+ let data = {
2126
+ userName: assignDetails[findUserIndex]?.userName,
2127
+ email: ele,
2128
+ mobileNumber: assignDetails[findUserIndex]?.mobileNumber,
2129
+ clientId: req.body.clientId,
2130
+ };
2131
+ let response = await createUser( data );
2132
+ if ( req.body.coverage == 'user' ) {
2133
+ assignDetails[findUserIndex]._id = response._id;
2134
+ }
1565
2135
  }
1566
- }
2136
+ } ) );
2137
+ return res.sendSuccess( { validate: true, data: assignDetails } );
1567
2138
  } catch ( e ) {
1568
2139
  logger.error( 'validateUser 2=>', e );
1569
2140
  return res.sendError( e, 500 );
1570
2141
  }
1571
2142
  };
1572
2143
 
2144
+ // export async function assignChecklistUser( req, res ) {
2145
+ // try {
2146
+ // let inputBody = req.body;
2147
+ // let assignDetails = inputBody.assignUsers;
2148
+ // let newUsers = inputBody.newUsers;
2149
+ // let checklistDetails = await checklistService.findOne( { _id: inputBody.checklistId } );
2150
+ // if ( !checklistDetails ) {
2151
+ // return res.sendError( 'No data found', 204 );
2152
+ // }
2153
+ // await Promise.all( newUsers.map( async ( user ) => {
2154
+ // let getUser = inputBody.assignUsers.find( ( ele ) => ele.userEmail.toLowerCase() == user.toLowerCase() );
2155
+ // let userData = {
2156
+ // userName: getUser.userName,
2157
+ // email: user,
2158
+ // mobileNumber: getUser?.phone,
2159
+ // clientId: inputBody.clientId,
2160
+ // };
2161
+ // await createUser( userData );
2162
+ // } ) );
2163
+ // let assignData = [];
2164
+ // await Promise.all( assignDetails.map( async ( assign ) => {
2165
+ // assign.checklistId = inputBody.taskId;
2166
+ // assign.checkListName = checklistDetails.checkListName;
2167
+ // assign.coverage = inputBody.coverage;
2168
+ // assign.clientId = inputBody.clientId;
2169
+ // assign.upload = inputBody.type;
2170
+ // let uploadData = await assignUsers( assign );
2171
+ // if ( uploadData ) {
2172
+ // if ( Array.isArray( uploadData ) ) {
2173
+ // assignData.push( ...uploadData );
2174
+ // } else {
2175
+ // assignData.push( uploadData );
2176
+ // }
2177
+ // }
2178
+ // } ) );
2179
+ // return res.sendSuccess( { idList: [ ...new Set( assignData.map( ( item ) => {
2180
+ // return { id: item?.assignId?.toString(), type: inputBody.coverage == 'store' ? typeof item.clusterName == 'undefined' ? 'store' : 'cluster' : typeof item.teamsName == 'undefined' ? 'user' : 'teams' };
2181
+ // } ) ) ], assignData } );
2182
+ // } catch ( e ) {
2183
+ // logger.error( { functionName: 'assignUser', error: e } );
2184
+ // return res.sendError( e, 500 );
2185
+ // }
2186
+ // }
2187
+
1573
2188
  async function uploadUser( req, res ) {
1574
2189
  try {
1575
2190
  let inputBody = req.body;
@@ -1944,6 +2559,8 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1944
2559
  insertdata.approver = getCLconfig?.approver || [];
1945
2560
  insertdata.remainder = getCLconfig?.remainder || [];
1946
2561
  insertdata.restrictAttendance = getCLconfig?.restrictAttendance;
2562
+ insertdata.coverage = getCLconfig?.coverage;
2563
+ insertdata.rawImageUpload = getCLconfig?.rawImageUpload || false;
1947
2564
 
1948
2565
  let collectSections = [];
1949
2566
  let sectionQuery = [];
@@ -1981,7 +2598,7 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1981
2598
  updatedchecklist = checklistDetails;
1982
2599
  }
1983
2600
  if ( updatedchecklist ) {
1984
- insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit );
2601
+ insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit );
1985
2602
  }
1986
2603
  }
1987
2604
  }
@@ -1992,7 +2609,322 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1992
2609
  }
1993
2610
  };
1994
2611
 
1995
- async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
2612
+ // async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
2613
+ // let getquestionQuery = [];
2614
+ // if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection' ].includes( getCLconfig.checkListType ) ) {
2615
+ // getquestionQuery.push(
2616
+ // {
2617
+ // $match: {
2618
+ // checkListId: new ObjectId( checklistId ),
2619
+ // checkFlag: true,
2620
+ // },
2621
+ // },
2622
+ // {
2623
+ // $group: {
2624
+ // '_id': '$store_id',
2625
+ // 'store_id': { $first: '$store_id' },
2626
+ // 'client_id': { $first: '$client_id' },
2627
+ // 'storeName': { $first: '$storeName' },
2628
+ // 'userId': { $first: '$userId' },
2629
+ // 'userEmail': { $first: '$userEmail' },
2630
+ // 'userName': { $first: '$userName' },
2631
+ // 'checkFlag': { $first: '$checkFlag' },
2632
+ // 'checkListId': { $first: '$checkListId' },
2633
+ // 'checkListName': { $first: '$checkListName' },
2634
+ // 'country': { $first: '$country' },
2635
+ // 'createdAt': { $first: '$createdAt' },
2636
+ // 'updatedAt': { $first: '$updatedAt' },
2637
+ // },
2638
+ // },
2639
+ // );
2640
+ // } else {
2641
+ // getquestionQuery.push( {
2642
+ // $match: {
2643
+ // checkListId: new ObjectId( checklistId ),
2644
+ // checkFlag: true,
2645
+ // isdeleted: false,
2646
+ // },
2647
+ // } );
2648
+ // }
2649
+ // let allQuestion = await assignedService.aggregate( getquestionQuery );
2650
+ // if ( allQuestion ) {
2651
+ // let userIdList = [];
2652
+ // let tokenList = [];
2653
+ // let notifyUserList = [];
2654
+ // let status = [ { checklistStatus: { $ne: 'open' } } ];
2655
+
2656
+ // for ( let element4 of allQuestion ) {
2657
+ // let getToken = await userService.findOne( { _id: element4.userId }, { fcmToken: 1 } );
2658
+ // if ( getToken && getToken?.fcmToken && element4?.sendNotification && showEdit ) {
2659
+ // tokenList.push( getToken.fcmToken );
2660
+ // }
2661
+ // if ( !element4?.sendNotification ) {
2662
+ // notifyUserList.push( { token: getToken?.fcmToken, storeName: element4.storeName, id: element4._id } );
2663
+ // }
2664
+ // if ( !getCLconfig?.allowedMultiSubmit ) {
2665
+ // let query;
2666
+ // if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
2667
+ // if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
2668
+ // let startDate; let endDate;
2669
+ // if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
2670
+ // startDate = dayjs.utc( date ).clone().startOf( 'week' );
2671
+ // endDate = dayjs.utc( date ).clone().endOf( 'week' );
2672
+ // } else {
2673
+ // startDate = dayjs.utc( date ).clone().startOf( 'month' );
2674
+ // endDate = dayjs.utc( date ).clone().endOf( 'month' );
2675
+ // }
2676
+ // query = {
2677
+ // sourceCheckList_id: getCLconfig._id,
2678
+ // $or: [
2679
+ // { submitTime: { $exists: true } },
2680
+ // ...status,
2681
+ // ],
2682
+ // userId: element4.userId,
2683
+ // store_id: element4.store_id,
2684
+ // $and: [ {
2685
+ // date_iso: {
2686
+ // $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
2687
+ // $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
2688
+ // } ],
2689
+ // };
2690
+ // } else {
2691
+ // if ( getCLconfig.schedule == 'range' ) {
2692
+ // query = {
2693
+ // sourceCheckList_id: getCLconfig._id,
2694
+ // $or: [
2695
+ // { submitTime: { $exists: true } },
2696
+ // ...status,
2697
+ // ],
2698
+ // userId: element4.userId,
2699
+ // store_id: element4.store_id,
2700
+ // $and: [
2701
+ // {
2702
+ // date_iso: {
2703
+ // $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
2704
+ // $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ),
2705
+ // },
2706
+ // },
2707
+ // ],
2708
+ // };
2709
+ // }
2710
+ // }
2711
+ // } else {
2712
+ // query = {
2713
+ // date_string: date,
2714
+ // sourceCheckList_id: getCLconfig._id,
2715
+ // $or: [
2716
+ // ...status,
2717
+ // { submitTime: { $exists: true } },
2718
+ // ],
2719
+ // userId: element4.userId,
2720
+ // store_id: element4.store_id,
2721
+ // };
2722
+ // }
2723
+ // let getsubmitDetails = await processedchecklist.find( query );
2724
+ // function findDifferences( obj1, obj2 ) {
2725
+ // return Object.keys( obj1 ).reduce( ( diff, key ) => {
2726
+ // if ( !isEqual( obj1[key], obj2[key] ) ) {
2727
+ // diff[key] = { value1: obj1[key], value2: obj2[key] };
2728
+ // }
2729
+ // return diff;
2730
+ // }, {} );
2731
+ // }
2732
+ // if ( getsubmitDetails.length ) {
2733
+ // if ( showEdit && ( ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) || getsubmitDetails[0].checklistStatus == 'inprogress' ) ) {
2734
+ // let modifiedCount = 0;
2735
+ // let questionList = insertdata.questionAnswers;
2736
+ // if ( getsubmitDetails[0].checkListName != getCLconfig.checkListName ) {
2737
+ // getsubmitDetails[0].checkListName = getCLconfig.checkListName;
2738
+ // }
2739
+ // if ( getsubmitDetails[0].checkListDescription != getCLconfig.checkListDescription ) {
2740
+ // getsubmitDetails[0].checkListDescription = getCLconfig.checkListDescription;
2741
+ // }
2742
+ // let sectionList = [];
2743
+ // for ( let [ index, section ] of questionList.entries() ) {
2744
+ // let checkExists = getsubmitDetails[0].questionAnswers.findIndex( ( sec ) => sec.sectionName == section?.sectionOldName || sec.sectionName == section.sectionName );
2745
+ // if ( checkExists != -1 ) {
2746
+ // getsubmitDetails[0].questionAnswers[index].section_id = section.section_id;
2747
+ // getsubmitDetails[0].questionAnswers[index].sectionName = section.sectionName;
2748
+ // let question = [];
2749
+ // section.questions.forEach( ( qns ) => {
2750
+ // let findQuestion = getsubmitDetails[0].questionAnswers[index].questions.findIndex( ( ele ) => ele.qname.trim() == qns?.oldQname?.trim() || ele.qname.trim() == qns.qname.trim() );
2751
+ // if ( findQuestion != -1 ) {
2752
+ // let data = JSON.parse( JSON.stringify( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] ) );
2753
+ // getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qno = qns.qno;
2754
+ // delete data.userAnswer;
2755
+ // delete data.parentanswer;
2756
+ // delete data.remarks;
2757
+ // delete data.linkquestionenabled;
2758
+ // if ( data.descriptivetype == null ) {
2759
+ // delete data.descriptivetype;
2760
+ // }
2761
+ // qns.answers.forEach( ( ans ) => {
2762
+ // delete ans.validationAnswer;
2763
+ // delete ans.answeroptionNumber;
2764
+ // } );
2765
+ // data.answers.forEach( ( ans ) => {
2766
+ // delete ans.index;
2767
+ // delete ans.validationAnswer;
2768
+ // delete ans.answeroptionNumber;
2769
+ // } );
2770
+ // const compare = findDifferences( data, qns );
2771
+ // if ( compare?.answerType || compare?.answers || compare?.linkType ) {
2772
+ // logger.info( 'compare =>', compare );
2773
+ // modifiedCount++;
2774
+ // question.push( qns );
2775
+ // } else {
2776
+ // getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qname = qns.qname;
2777
+ // question.push( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] );
2778
+ // }
2779
+ // } else {
2780
+ // modifiedCount++;
2781
+ // question.push( qns );
2782
+ // }
2783
+ // } );
2784
+ // getsubmitDetails[0].questionAnswers[index].questions = question;
2785
+ // sectionList.push( getsubmitDetails[0].questionAnswers[index] );
2786
+ // } else {
2787
+ // modifiedCount++;
2788
+ // sectionList.push( section );
2789
+ // }
2790
+ // }
2791
+ // getsubmitDetails[0].questionAnswers = sectionList;
2792
+ // if ( modifiedCount ) {
2793
+ // getsubmitDetails[0].checklistStatus = 'inprogress';
2794
+ // getsubmitDetails[0].date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
2795
+ // getsubmitDetails[0].date_iso = new Date( date );
2796
+ // getsubmitDetails[0].redoStatus = false;
2797
+ // getsubmitDetails[0].approvalStatus = false;
2798
+ // }
2799
+ // let data = { ...getsubmitDetails[0]._doc };
2800
+ // await processedchecklist.updateOne( { _id: getsubmitDetails[0]._id }, data );
2801
+ // if ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) {
2802
+ // console.log( editSubmit );
2803
+ // let user = {
2804
+ // _id: getsubmitDetails[0].userId,
2805
+ // clientId: getsubmitDetails[0].client_id,
2806
+ // };
2807
+ // updateOpenSearch( user, { processedcheckListId: getsubmitDetails[0]._id, date: getsubmitDetails[0].date_string } );
2808
+ // }
2809
+ // }
2810
+ // if ( getsubmitDetails[0]?.checklistStatus == 'submit' ) {
2811
+ // userIdList.push( element4._id );
2812
+ // continue;
2813
+ // }
2814
+ // }
2815
+ // }
2816
+ // delete element4._id;
2817
+ // delete element4.checkFlag;
2818
+ // delete element4.isdeleted;
2819
+ // delete element4.createdAt;
2820
+ // delete element4.updatedAt;
2821
+ // element4.checkListId = updatedchecklist._id;
2822
+ // element4.checkListName = getCLconfig.checkListName;
2823
+ // element4.checkListDescription = getCLconfig.checkListDescription;
2824
+ // element4.date_iso = new Date( date );
2825
+ // element4.date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
2826
+ // element4.allowedOverTime = getCLconfig.allowedOverTime;
2827
+ // element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
2828
+ // element4.scheduleStartTime = getCLconfig.scheduleStartTime;
2829
+ // element4.scheduleStartTime_iso = startTimeIso.format();
2830
+ // element4.scheduleEndTime = getCLconfig.scheduleEndTime;
2831
+ // element4.scheduleEndTime_iso = endTimeIso.format();
2832
+ // element4.createdBy = new ObjectId( getCLconfig.createdBy );
2833
+ // element4.createdByName = getCLconfig.createdByName;
2834
+ // element4.sourceCheckList_id = getCLconfig._id;
2835
+ // element4.checkListType = getCLconfig.checkListType;
2836
+ // element4.storeCount = getCLconfig.storeCount;
2837
+ // element4.questionCount = getCLconfig.questionCount;
2838
+ // element4.publishDate = getCLconfig.publishDate;
2839
+ // element4.locationCount = getCLconfig.locationCount;
2840
+ // element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
2841
+ // element4.approvalEnable = getCLconfig.approver.length ? true : false;
2842
+ // element4.remainder = getCLconfig?.remainder || [];
2843
+ // element4.restrictAttendance = getCLconfig?.restrictAttendance;
2844
+ // }
2845
+ // if ( userIdList.length ) {
2846
+ // allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
2847
+ // }
2848
+ // if ( allQuestion ) {
2849
+ // if ( getCLconfig?.allowedMultiSubmit || processId ) {
2850
+ // if ( processId ) {
2851
+ // let processedDetails = await processedchecklist.findOne( { _id: processId } );
2852
+ // if ( processedDetails ) {
2853
+ // let submitUser = allQuestion.find( ( item ) => item.userId.toString() == processedDetails.userId.toString() && item.store_id == processedDetails.store_id );
2854
+ // await processedchecklist.insertMany( submitUser );
2855
+ // }
2856
+ // } else {
2857
+ // let deleteInprogressQuery = {
2858
+ // date_string: insertdata.date_string,
2859
+ // date_iso: insertdata.date_iso,
2860
+ // client_id: insertdata.client_id,
2861
+ // checkListId: updatedchecklist._id,
2862
+ // checklistStatus: { $nin: [ 'submit', 'inprogress' ] },
2863
+ // redoStatus: false,
2864
+ // };
2865
+ // await processedchecklist.deleteMany( deleteInprogressQuery );
2866
+ // deleteInprogressQuery.checklistStatus = 'inprogress';
2867
+ // deleteInprogressQuery.redoStatus = false;
2868
+ // let getInprogressData = await processedchecklist.find( deleteInprogressQuery, { userId: 1, store_id: 1 } );
2869
+ // if ( getInprogressData ) {
2870
+ // allQuestion = allQuestion.filter( ( item ) => {
2871
+ // let inprogressData = getInprogressData.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
2872
+ // if ( !inprogressData ) {
2873
+ // return item;
2874
+ // }
2875
+ // } );
2876
+ // }
2877
+ // if ( allQuestion.length ) {
2878
+ // await processedchecklist.insertMany( allQuestion );
2879
+ // }
2880
+ // }
2881
+ // } else {
2882
+ // let unAssignedList = allQuestion.reduce( ( acc, item ) => {
2883
+ // if ( !acc[item.userEmail] ) {
2884
+ // acc[item.userEmail]=[ item.store_id ];
2885
+ // } else {
2886
+ // acc[item.userEmail].push( item.store_id );
2887
+ // }
2888
+ // return acc;
2889
+ // }, {} );
2890
+
2891
+ // let userList = Object.keys( unAssignedList );
2892
+
2893
+ // await processedchecklist.deleteMany( { userEmail: { $nin: userList }, date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, checklistStatus: { $nin: [ 'submit' ] } } );
2894
+
2895
+ // for ( let key in unAssignedList ) {
2896
+ // if ( unAssignedList.hasOwnProperty( key ) ) {
2897
+ // await processedchecklist.deleteMany( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, $and: [ { userEmail: key }, { store_id: { $nin: unAssignedList[key] } } ], checklistStatus: { $nin: [ 'submit' ] } } );
2898
+ // }
2899
+ // }
2900
+
2901
+
2902
+ // Promise.all( allQuestion.map( async ( ele ) => {
2903
+ // await processedchecklist.updateOne( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, userEmail: ele.userEmail, store_id: ele.store_id }, ele );
2904
+ // } ) );
2905
+ // }
2906
+
2907
+ // tokenList.forEach( ( item ) => {
2908
+ // const title = `${getCLconfig.checkListName}`;
2909
+ // const description = `Checklist has been updated and re-published!`;
2910
+ // const fcmToken = item;
2911
+ // sendPushNotification( title, description, fcmToken );
2912
+ // } );
2913
+
2914
+ // notifyUserList.forEach( ( item ) => {
2915
+ // const title = `New Checklist Assigned ${item.storeName}`;
2916
+ // const description = `The ${getCLconfig.checkListName} checklist has been assigned to ${item.storeName} for the first time.complete to avoid compliance.`;
2917
+ // const fcmToken = item.token;
2918
+ // sendPushNotification( title, description, fcmToken );
2919
+ // } );
2920
+
2921
+ // let updateUserList = notifyUserList.map( ( ele ) => ele.id );
2922
+ // await assignedService.updateMany( { _id: { $in: updateUserList } }, { sendNotification: true } );
2923
+ // }
2924
+ // }
2925
+ // }
2926
+
2927
+ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
1996
2928
  let getquestionQuery = [];
1997
2929
  if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection' ].includes( getCLconfig.checkListType ) ) {
1998
2930
  getquestionQuery.push(
@@ -2024,86 +2956,202 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2024
2956
  getquestionQuery.push( {
2025
2957
  $match: {
2026
2958
  checkListId: new ObjectId( checklistId ),
2027
- checkFlag: true,
2028
2959
  isdeleted: false,
2029
2960
  },
2030
2961
  } );
2031
2962
  }
2032
2963
  let allQuestion = await assignedService.aggregate( getquestionQuery );
2033
2964
  if ( allQuestion ) {
2965
+ let assignList = [];
2966
+ if ( getCLconfig.coverage == 'store' ) {
2967
+ let clusterList = allQuestion.filter( ( ele ) => ele?.clusterName ).map( ( item ) => item.assignId );
2968
+ if ( clusterList.length ) {
2969
+ let clusterDetails = await clusterServices.findcluster( { _id: { $in: clusterList } } );
2970
+ if ( clusterDetails.length ) {
2971
+ let idList = clusterDetails.flatMap( ( item ) => item.stores.map( ( ele ) => ele.store ) );
2972
+ let getStoreDetails = await storeService.find( { _id: { $in: idList }, status: 'active' } );
2973
+ if ( getStoreDetails.length ) {
2974
+ getStoreDetails = getStoreDetails.filter( ( store ) => {
2975
+ let findStore = allQuestion.find( ( storeList ) => storeList.assignId.toString() == store._id.toString() );
2976
+ if ( findStore ) {
2977
+ return store?.spocDetails?.[0]?.email.toLowerCase() != findStore.userEmail.toLowerCase();
2978
+ } else {
2979
+ return true;
2980
+ }
2981
+ } );
2982
+ assignList = await Promise.all( getStoreDetails.map( async ( store ) => {
2983
+ let userQuery = [
2984
+ {
2985
+ $project: {
2986
+ newEmail: { $toLower: '$email' },
2987
+ isActive: 1,
2988
+ clientId: 1,
2989
+ userName: 1,
2990
+ email: 1,
2991
+ },
2992
+ },
2993
+ {
2994
+ $match: {
2995
+ newEmail: store?.spocDetails?.[0]?.email.toLowerCase(),
2996
+ isActive: true,
2997
+ clientId: store.clientId,
2998
+ },
2999
+ },
3000
+ ];
3001
+ let userDetails = await userService.aggregate( userQuery );
3002
+ if ( !userDetails.length ) {
3003
+ let data = {
3004
+ clientId: store.clientId,
3005
+ userName: store.spocDetails?.[0]?.name,
3006
+ mobileNumber: store.spocDetails?.[0]?.phone || '',
3007
+ email: store.spocDetails[0].email,
3008
+ };
3009
+ userDetails = await createUser( data );
3010
+ userDetails = [ userDetails ];
3011
+ }
3012
+ let data = {
3013
+ store_id: store?.storeId,
3014
+ storeName: store?.storeName,
3015
+ userId: userDetails?.[0]?._id,
3016
+ userName: userDetails?.[0]?.userName,
3017
+ userEmail: userDetails?.[0]?.email,
3018
+ userPhone: userDetails?.[0]?.mobileNumber,
3019
+ city: store?.storeProfile?.city,
3020
+ country: store?.storeProfile?.country,
3021
+ checkFlag: true,
3022
+ checkListId: getCLconfig._id,
3023
+ checkListName: getCLconfig.checkListName,
3024
+ client_id: getCLconfig.client_id,
3025
+ };
3026
+ return data;
3027
+ } ) );
3028
+ }
3029
+ }
3030
+ }
3031
+ allQuestion = allQuestion.filter( ( ele ) => !clusterList.includes( ele.assignId ) );
3032
+ }
3033
+ if ( getCLconfig.coverage == 'user' ) {
3034
+ let teamsList = allQuestion.filter( ( ele ) => ele?.teamName ).map( ( item ) => item.assignId );
3035
+ if ( teamsList.length ) {
3036
+ let teamDetails = await teamsServices.findteams( { _id: { $in: teamsList } } );
3037
+ if ( teamDetails.length ) {
3038
+ let idList = [ ...teamDetails.flatMap( ( item ) => item.users.map( ( ele ) => ele.userId ) ), ...teamDetails.flatMap( ( item ) => item.Teamlead.map( ( ele ) => ele.userId ) ) ];
3039
+ let userIdList = allQuestion.filter( ( qn ) => !qn?.teamName ).map( ( qn ) => qn.assignId.toString() );
3040
+ idList = idList.filter( ( id ) => !userIdList.includes( id.toString() ) );
3041
+ let getUserDetails = await userService.find( { _id: { $in: idList } } );
3042
+ if ( getUserDetails.length ) {
3043
+ assignList = getUserDetails.map( ( user ) => {
3044
+ let data = {
3045
+ store_id: '',
3046
+ storeName: '',
3047
+ userId: user._id,
3048
+ userName: user.userName,
3049
+ userEmail: user.email,
3050
+ userPhone: user?.mobileNumber,
3051
+ city: '',
3052
+ country: '',
3053
+ checkFlag: true,
3054
+ checkListId: getCLconfig._id,
3055
+ checkListName: getCLconfig.checkListName,
3056
+ client_id: getCLconfig.client_id,
3057
+ };
3058
+ return data;
3059
+ } );
3060
+ }
3061
+ }
3062
+ }
3063
+ allQuestion = allQuestion.filter( ( ele ) => !teamsList.includes( ele.assignId ) );
3064
+ }
3065
+ allQuestion = [ ...allQuestion, ...assignList ];
2034
3066
  let userIdList = [];
2035
3067
  let tokenList = [];
2036
3068
  let notifyUserList = [];
2037
3069
  let status = [ { checklistStatus: { $ne: 'open' } } ];
2038
-
2039
- for ( let element4 of allQuestion ) {
2040
- let getToken = await userService.findOne( { _id: element4.userId }, { fcmToken: 1 } );
2041
- if ( getToken && getToken?.fcmToken && element4?.sendNotification && showEdit ) {
2042
- tokenList.push( getToken.fcmToken );
2043
- }
2044
- if ( !element4?.sendNotification ) {
2045
- notifyUserList.push( { token: getToken?.fcmToken, storeName: element4.storeName, id: element4._id } );
2046
- }
2047
- if ( !getCLconfig?.allowedMultiSubmit ) {
2048
- let query;
2049
- if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
2050
- if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
2051
- let startDate; let endDate;
2052
- if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
2053
- startDate = dayjs.utc( date ).clone().startOf( 'week' );
2054
- endDate = dayjs.utc( date ).clone().endOf( 'week' );
2055
- } else {
2056
- startDate = dayjs.utc( date ).clone().startOf( 'month' );
2057
- endDate = dayjs.utc( date ).clone().endOf( 'month' );
2058
- }
3070
+ let assignUserList = [];
3071
+ let userList = allQuestion.map( ( item ) => item.userId );
3072
+ let submittedDetails = [];
3073
+ let userDetails = await userService.find( { _id: { $in: userList } }, { fcmToken: 1 } );
3074
+ userDetails = new Map( userDetails.map( ( ele ) => [ ele._id.toString(), ele.fcmToken ] ) );
3075
+ if ( !getCLconfig?.allowedMultiSubmit ) {
3076
+ let query;
3077
+ if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
3078
+ if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
3079
+ let startDate; let endDate;
3080
+ if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
3081
+ startDate = dayjs.utc( date ).clone().startOf( 'week' );
3082
+ endDate = dayjs.utc( date ).clone().endOf( 'week' );
3083
+ } else {
3084
+ startDate = dayjs.utc( date ).clone().startOf( 'month' );
3085
+ endDate = dayjs.utc( date ).clone().endOf( 'month' );
3086
+ }
3087
+ query = {
3088
+ sourceCheckList_id: getCLconfig._id,
3089
+ $or: [
3090
+ { submitTime: { $exists: true } },
3091
+ ...status,
3092
+ ],
3093
+ // userId: { $in: userList },
3094
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3095
+ $and: [ {
3096
+ date_iso: {
3097
+ $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
3098
+ $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
3099
+ } ],
3100
+ };
3101
+ } else {
3102
+ if ( getCLconfig.schedule == 'range' ) {
2059
3103
  query = {
2060
3104
  sourceCheckList_id: getCLconfig._id,
2061
3105
  $or: [
2062
3106
  { submitTime: { $exists: true } },
2063
3107
  ...status,
2064
3108
  ],
2065
- userId: element4.userId,
2066
- store_id: element4.store_id,
2067
- $and: [ {
2068
- date_iso: {
2069
- $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
2070
- $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
2071
- } ],
2072
- };
2073
- } else {
2074
- if ( getCLconfig.schedule == 'range' ) {
2075
- query = {
2076
- sourceCheckList_id: getCLconfig._id,
2077
- $or: [
2078
- { submitTime: { $exists: true } },
2079
- ...status,
2080
- ],
2081
- userId: element4.userId,
2082
- store_id: element4.store_id,
2083
- $and: [
2084
- {
2085
- date_iso: {
2086
- $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
2087
- $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ),
2088
- },
3109
+ // userId: element4.userId,
3110
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3111
+ $and: [
3112
+ {
3113
+ date_iso: {
3114
+ $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
3115
+ $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ),
2089
3116
  },
2090
- ],
2091
- };
2092
- }
3117
+ },
3118
+ ],
3119
+ };
2093
3120
  }
3121
+ }
3122
+ } else {
3123
+ query = {
3124
+ date_string: date,
3125
+ sourceCheckList_id: getCLconfig._id,
3126
+ $or: [
3127
+ ...status,
3128
+ { submitTime: { $exists: true } },
3129
+ ],
3130
+ // userId: element4.userId,
3131
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3132
+ };
3133
+ }
3134
+ submittedDetails = await processedchecklist.find( query );
3135
+ }
3136
+ await Promise.all( allQuestion.map( async ( element4 ) => {
3137
+ let getToken = userDetails.get( element4.userId.toString() );
3138
+ if ( getToken && element4?.sendNotification && showEdit ) {
3139
+ tokenList.push( getToken );
3140
+ }
3141
+ if ( !element4?.sendNotification ) {
3142
+ notifyUserList.push( { token: getToken, storeName: element4.storeName, id: element4._id } );
3143
+ }
3144
+ if ( !getCLconfig?.allowedMultiSubmit ) {
3145
+ let getsubmitDetails;
3146
+ if ( getCLconfig.coverage == 'store' ) {
3147
+ getsubmitDetails = submittedDetails.find( ( checklist ) => checklist.userId.toString() == element4.userId.toString() && checklist.store_id == element4.store_id );
2094
3148
  } else {
2095
- query = {
2096
- date_string: date,
2097
- sourceCheckList_id: getCLconfig._id,
2098
- $or: [
2099
- ...status,
2100
- { submitTime: { $exists: true } },
2101
- ],
2102
- userId: element4.userId,
2103
- store_id: element4.store_id,
2104
- };
3149
+ getsubmitDetails = submittedDetails.find( ( checklist ) => checklist.userId.toString() == element4.userId.toString() );
3150
+ }
3151
+ if ( getsubmitDetails ) {
3152
+ getsubmitDetails = [ getsubmitDetails ];
3153
+ console.log( submittedDetails, getsubmitDetails );
2105
3154
  }
2106
- let getsubmitDetails = await processedchecklist.find( query );
2107
3155
  function findDifferences( obj1, obj2 ) {
2108
3156
  return Object.keys( obj1 ).reduce( ( diff, key ) => {
2109
3157
  if ( !isEqual( obj1[key], obj2[key] ) ) {
@@ -2112,7 +3160,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2112
3160
  return diff;
2113
3161
  }, {} );
2114
3162
  }
2115
- if ( getsubmitDetails.length ) {
3163
+ if ( getsubmitDetails?.length ) {
2116
3164
  if ( showEdit && ( ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) || getsubmitDetails[0].checklistStatus == 'inprogress' ) ) {
2117
3165
  let modifiedCount = 0;
2118
3166
  let questionList = insertdata.questionAnswers;
@@ -2133,6 +3181,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2133
3181
  let findQuestion = getsubmitDetails[0].questionAnswers[index].questions.findIndex( ( ele ) => ele.qname.trim() == qns?.oldQname?.trim() || ele.qname.trim() == qns.qname.trim() );
2134
3182
  if ( findQuestion != -1 ) {
2135
3183
  let data = JSON.parse( JSON.stringify( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] ) );
3184
+ getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qno = qns.qno;
2136
3185
  delete data.userAnswer;
2137
3186
  delete data.parentanswer;
2138
3187
  delete data.remarks;
@@ -2177,78 +3226,95 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2177
3226
  getsubmitDetails[0].date_iso = new Date( date );
2178
3227
  getsubmitDetails[0].redoStatus = false;
2179
3228
  getsubmitDetails[0].approvalStatus = false;
2180
- } else {
2181
- if ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) {
2182
- console.log( editSubmit );
2183
- let user = {
2184
- _id: getsubmitDetails[0].userId,
2185
- clientId: getsubmitDetails[0].client_id,
2186
- };
2187
- updateOpenSearch( user, { processedcheckListId: getsubmitDetails[0]._id, date: getsubmitDetails[0].date_string } );
2188
- }
2189
3229
  }
2190
3230
  let data = { ...getsubmitDetails[0]._doc };
2191
3231
  await processedchecklist.updateOne( { _id: getsubmitDetails[0]._id }, data );
3232
+ if ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) {
3233
+ let user = {
3234
+ _id: getsubmitDetails[0].userId,
3235
+ clientId: getsubmitDetails[0].client_id,
3236
+ };
3237
+ updateOpenSearch( user, { processedcheckListId: getsubmitDetails[0]._id, date: getsubmitDetails[0].date_string } );
3238
+ }
2192
3239
  }
2193
3240
  if ( getsubmitDetails[0]?.checklistStatus == 'submit' ) {
2194
3241
  userIdList.push( element4._id );
2195
- continue;
2196
3242
  }
2197
3243
  }
2198
3244
  }
2199
- delete element4._id;
2200
- delete element4.checkFlag;
2201
- delete element4.isdeleted;
2202
- delete element4.createdAt;
2203
- delete element4.updatedAt;
2204
- element4.checkListId = updatedchecklist._id;
2205
- element4.checkListName = getCLconfig.checkListName;
2206
- element4.checkListDescription = getCLconfig.checkListDescription;
2207
- element4.date_iso = new Date( date );
2208
- element4.date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
2209
- element4.allowedOverTime = getCLconfig.allowedOverTime;
2210
- element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
2211
- element4.scheduleStartTime = getCLconfig.scheduleStartTime;
2212
- element4.scheduleStartTime_iso = startTimeIso.format();
2213
- element4.scheduleEndTime = getCLconfig.scheduleEndTime;
2214
- element4.scheduleEndTime_iso = endTimeIso.format();
2215
- element4.createdBy = new ObjectId( getCLconfig.createdBy );
2216
- element4.createdByName = getCLconfig.createdByName;
2217
- element4.sourceCheckList_id = getCLconfig._id;
2218
- element4.checkListType = getCLconfig.checkListType;
2219
- element4.storeCount = getCLconfig.storeCount;
2220
- element4.questionCount = getCLconfig.questionCount;
2221
- element4.publishDate = getCLconfig.publishDate;
2222
- element4.locationCount = getCLconfig.locationCount;
2223
- element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
2224
- element4.approvalEnable = getCLconfig.approver.length ? true : false;
2225
- element4.remainder = getCLconfig?.remainder || [];
2226
- element4.restrictAttendance = getCLconfig?.restrictAttendance;
2227
- }
3245
+ if ( !userIdList.includes( element4._id ) ) {
3246
+ delete element4._id;
3247
+ delete element4.checkFlag;
3248
+ delete element4.isdeleted;
3249
+ delete element4.createdAt;
3250
+ delete element4.updatedAt;
3251
+ element4.checkListId = updatedchecklist._id;
3252
+ element4.checkListName = getCLconfig.checkListName;
3253
+ element4.checkListDescription = getCLconfig.checkListDescription;
3254
+ element4.date_iso = new Date( date );
3255
+ element4.date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
3256
+ element4.allowedOverTime = getCLconfig.allowedOverTime;
3257
+ element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
3258
+ element4.scheduleStartTime = getCLconfig.scheduleStartTime;
3259
+ element4.scheduleStartTime_iso = startTimeIso.format();
3260
+ element4.scheduleEndTime = getCLconfig.scheduleEndTime;
3261
+ element4.scheduleEndTime_iso = endTimeIso.format();
3262
+ element4.createdBy = new ObjectId( getCLconfig.createdBy );
3263
+ element4.createdByName = getCLconfig.createdByName;
3264
+ element4.sourceCheckList_id = getCLconfig._id;
3265
+ element4.checkListType = getCLconfig.checkListType;
3266
+ element4.storeCount = getCLconfig.storeCount;
3267
+ element4.questionCount = getCLconfig.questionCount;
3268
+ element4.publishDate = getCLconfig.publishDate;
3269
+ element4.locationCount = getCLconfig.locationCount;
3270
+ element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
3271
+ element4.approvalEnable = getCLconfig.approver.length ? true : false;
3272
+ element4.remainder = getCLconfig?.remainder || [];
3273
+ element4.restrictAttendance = getCLconfig?.restrictAttendance;
3274
+ element4.coverage = getCLconfig?.coverage;
3275
+ element4.rawImageUpload = getCLconfig?.rawImageUpload || false;
3276
+ assignUserList.push( { ...element4 } );
3277
+ }
3278
+ } ) );
3279
+
2228
3280
  if ( userIdList.length ) {
2229
- allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
3281
+ assignUserList = assignUserList.filter( ( item ) => typeof item._id == 'undefined' );
2230
3282
  }
2231
- if ( allQuestion ) {
3283
+ if ( assignUserList ) {
2232
3284
  if ( getCLconfig?.allowedMultiSubmit || processId ) {
2233
3285
  if ( processId ) {
2234
3286
  let processedDetails = await processedchecklist.findOne( { _id: processId } );
2235
3287
  if ( processedDetails ) {
2236
- let submitUser = allQuestion.find( ( item ) => item.userId.toString() == processedDetails.userId.toString() && item.store_id == processedDetails.store_id );
3288
+ let submitUser = assignUserList.find( ( item ) => getCLconfig.coverage == 'store' ? item.userId.toString() == processedDetails.userId.toString() && item.store_id == processedDetails.store_id : item.userId.toString() == processedDetails.userId.toString() );
2237
3289
  await processedchecklist.insertMany( submitUser );
2238
3290
  }
2239
3291
  } else {
2240
- let deleteQuery = {
3292
+ let deleteInprogressQuery = {
2241
3293
  date_string: insertdata.date_string,
2242
3294
  date_iso: insertdata.date_iso,
2243
3295
  client_id: insertdata.client_id,
2244
3296
  checkListId: updatedchecklist._id,
2245
- checklistStatus: { $nin: [ 'submit' ] },
3297
+ checklistStatus: { $nin: [ 'submit', 'inprogress' ] },
3298
+ redoStatus: false,
2246
3299
  };
2247
- await processedchecklist.deleteMany( deleteQuery );
2248
- await processedchecklist.insertMany( allQuestion );
3300
+ await processedchecklist.deleteMany( deleteInprogressQuery );
3301
+ deleteInprogressQuery.checklistStatus = 'inprogress';
3302
+ deleteInprogressQuery.redoStatus = false;
3303
+ let getInprogressData = await processedchecklist.find( deleteInprogressQuery, { userId: 1, store_id: 1 } );
3304
+ if ( getInprogressData ) {
3305
+ assignUserList = assignUserList.filter( ( item ) => {
3306
+ let inprogressData = getInprogressData.find( ( ele ) => getCLconfig.coverage == 'store' ? ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id : ele.userId.toString() == item.userId.toString() );
3307
+ if ( !inprogressData ) {
3308
+ return item;
3309
+ }
3310
+ } );
3311
+ }
3312
+ if ( assignUserList.length ) {
3313
+ await processedchecklist.insertMany( assignUserList );
3314
+ }
2249
3315
  }
2250
3316
  } else {
2251
- let unAssignedList = allQuestion.reduce( ( acc, item ) => {
3317
+ let unAssignedList = assignUserList.reduce( ( acc, item ) => {
2252
3318
  if ( !acc[item.userEmail] ) {
2253
3319
  acc[item.userEmail]=[ item.store_id ];
2254
3320
  } else {
@@ -2260,17 +3326,36 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2260
3326
  let userList = Object.keys( unAssignedList );
2261
3327
 
2262
3328
  await processedchecklist.deleteMany( { userEmail: { $nin: userList }, date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, checklistStatus: { $nin: [ 'submit' ] } } );
2263
-
2264
- for ( let key in unAssignedList ) {
2265
- if ( unAssignedList.hasOwnProperty( key ) ) {
2266
- await processedchecklist.deleteMany( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, $and: [ { userEmail: key }, { store_id: { $nin: unAssignedList[key] } } ], checklistStatus: { $nin: [ 'submit' ] } } );
3329
+ if ( getCLconfig.coverage == 'store' ) {
3330
+ for ( let key in unAssignedList ) {
3331
+ if ( unAssignedList.hasOwnProperty( key ) ) {
3332
+ await processedchecklist.deleteMany( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, $and: [ { userEmail: key }, { store_id: { $nin: unAssignedList[key] } } ], checklistStatus: { $nin: [ 'submit' ] } } );
3333
+ }
2267
3334
  }
2268
3335
  }
2269
3336
 
3337
+ let inprogressData = await processedchecklist.find( {
3338
+ date_string: insertdata.date_string,
3339
+ date_iso: insertdata.date_iso,
3340
+ client_id: insertdata.client_id,
3341
+ checkListId: updatedchecklist._id,
3342
+ checklistStatus: 'inprogress',
3343
+ }, { userId: 1, store_id: 1 } );
3344
+
3345
+ if ( inprogressData.length ) {
3346
+ assignUserList = assignUserList.filter( ( item ) => {
3347
+ let findData = inprogressData.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
3348
+ if ( !findData ) {
3349
+ return item;
3350
+ }
3351
+ } );
3352
+ }
2270
3353
 
2271
- Promise.all( allQuestion.map( async ( ele ) => {
2272
- await processedchecklist.updateOne( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, userEmail: ele.userEmail, store_id: ele.store_id }, ele );
2273
- } ) );
3354
+ await processedchecklist.deleteMany( { date_string: insertdata.date_string,
3355
+ date_iso: insertdata.date_iso,
3356
+ client_id: insertdata.client_id,
3357
+ checkListId: updatedchecklist._id, checklistStatus: 'open' } );
3358
+ await processedchecklist.insertMany( assignUserList );
2274
3359
  }
2275
3360
 
2276
3361
  tokenList.forEach( ( item ) => {
@@ -2345,11 +3430,11 @@ async function updateOpenSearch( user, data ) {
2345
3430
  export const aiChecklist = async ( req, res ) => {
2346
3431
  try {
2347
3432
  let storeDetails = await storeService.count( { clientId: req.query.clientId, status: 'active' } );
2348
- let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring' ];
3433
+ let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall' ];
2349
3434
  let checklistDetails = [];
2350
3435
  let publishList = [];
2351
3436
  let unpublishList = [];
2352
- publishList = await checklistService.find( { client_id: req.query.clientId, checkListType: { $in: aiList } }, { publish: 1, checkListName: 1, checkListType: 1, client_id: 1, checkListDescription: 1 } );
3437
+ publishList = await checklistService.find( { client_id: req.query.clientId, checkListType: { $in: aiList } }, { publish: 1, checkListName: 1, checkListType: 1, client_id: 1, checkListDescription: 1, storeCount: 1 } );
2353
3438
  if ( publishList.length ) {
2354
3439
  let existList = publishList.map( ( item ) => item.checkListType );
2355
3440
  aiList = aiList.filter( ( item ) => !existList.includes( item ) );
@@ -2358,7 +3443,9 @@ export const aiChecklist = async ( req, res ) => {
2358
3443
  checklistDetails = [ ...publishList, ...unpublishList ];
2359
3444
 
2360
3445
  checklistDetails.forEach( ( item ) => {
2361
- item.storeCount = storeDetails;
3446
+ if ( ![ 'mobileusagedetection', 'storeopenandclose', 'cleaning', 'scrum' ].includes( item.checkListType ) ) {
3447
+ item.storeCount = storeDetails;
3448
+ }
2362
3449
  } );
2363
3450
 
2364
3451
  return res.sendSuccess( checklistDetails );
@@ -2534,3 +3621,441 @@ export const preDefinedChecklist = async ( req, res ) => {
2534
3621
  }
2535
3622
  };
2536
3623
 
3624
+ export const selectAssign = async ( req, res ) => {
3625
+ try {
3626
+ let requestData = req.body;
3627
+ let resuldData;
3628
+ if ( requestData.coverage == 'store' ) {
3629
+ // //Select Store and cluster
3630
+ if ( requestData.assignType == 'store' ) {
3631
+ let storeQuery = [
3632
+ { $match: { clientId: requestData.clientId, status: 'active' } },
3633
+ {
3634
+ $project: {
3635
+ storeName: 1,
3636
+ storeId: 1,
3637
+ type: 'store',
3638
+ userName: { $arrayElemAt: [ '$spocDetails.name', 0 ] },
3639
+ userEmail: { $arrayElemAt: [ '$spocDetails.email', 0 ] },
3640
+ contact: { $arrayElemAt: [ '$spocDetails.contact', 0 ] },
3641
+ city: '$storeProfile.city',
3642
+ openTime: '$storeProfile.open',
3643
+ closeTime: '$storeProfile.close',
3644
+ },
3645
+ },
3646
+
3647
+ ];
3648
+ resuldData = await storeService.aggregate( storeQuery );
3649
+ } else {
3650
+ let clusterQuery = [
3651
+ { $match: { clientId: requestData.clientId } },
3652
+ { $project: { 'clusterName': 1, 'type': 'cluster' } },
3653
+ ];
3654
+ resuldData = await clusterServices.aggregateCluster( clusterQuery );
3655
+ }
3656
+ // console.log( 'getStores =>', getStores );
3657
+ // console.log( 'getClusters =>', getClusters );
3658
+ } else if ( requestData.coverage == 'user' ) {
3659
+ // //Select User and Teams
3660
+ if ( requestData.assignType == 'user' ) {
3661
+ let userQuery = [
3662
+ { $match: { clientId: requestData.clientId, isActive: true } },
3663
+ { $project: { 'userEmail': '$email', 'userName': 1, 'type': 'user' } },
3664
+ ];
3665
+ resuldData = await userService.aggregate( userQuery );
3666
+ } else {
3667
+ let teamQuery = [
3668
+ { $match: { clientId: requestData.clientId } },
3669
+ { $project: { 'teamName': 1, 'type': 'teams' } },
3670
+ ];
3671
+ resuldData = await teamsServices.aggregateTeams( teamQuery );
3672
+ }
3673
+ // let getUsers = await userService.aggregate( userQuery );
3674
+ // console.log( 'getUsers =>', getUsers );
3675
+
3676
+ // let getTeams = await teamsServices.aggregateTeams( teamQuery );
3677
+ // console.log( 'getTeams =>', getTeams );
3678
+ }
3679
+ return res.sendSuccess( { 'totalCount': resuldData.length, 'data': resuldData } );
3680
+ } catch ( e ) {
3681
+ console.log( 'e =>', e );
3682
+ logger.error( 'selectAssign =>', e );
3683
+ return res.sendError( e, 500 );
3684
+ }
3685
+ };
3686
+
3687
+ async function assignUsers( data ) {
3688
+ let assignedData;
3689
+ if ( data?.type == 'cluster' ) {
3690
+ let clusterDetails = await clusterServices.findcluster( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3691
+ if ( clusterDetails.length ) {
3692
+ let clusterList = clusterDetails[0].stores.map( ( ele ) => ele.store );
3693
+ let storeDetails = await storeService.find( { _id: { $in: clusterList }, status: 'active' } );
3694
+ assignedData = await Promise.all( storeDetails.map( async ( store ) => {
3695
+ let userData = {
3696
+ storeId: store.storeId,
3697
+ storeName: store.storeName,
3698
+ userName: store.spocDetails?.[0]?.name,
3699
+ userEmail: store.spocDetails?.[0]?.email,
3700
+ clusterName: clusterDetails?.[0]?.clusterName,
3701
+ id: clusterDetails?.[0]?._id,
3702
+ };
3703
+ return userData;
3704
+ } ) );
3705
+ }
3706
+ } else {
3707
+ let teamDetails = await teamsServices.findteams( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3708
+ if ( teamDetails.length ) {
3709
+ let userIdList = [ ...teamDetails[0].users.map( ( ele ) => ele.userId ), ...teamDetails[0].Teamlead.map( ( ele ) => ele.userId ) ];
3710
+ let userDetails = await userService.find( { _id: userIdList } );
3711
+ assignedData = userDetails.map( ( user ) => {
3712
+ let userData = {
3713
+ userName: user.userName,
3714
+ userEmail: user.email,
3715
+ teamName: teamDetails?.[0]?.teamName,
3716
+ id: teamDetails?.[0]?._id,
3717
+ };
3718
+ return userData;
3719
+ } );
3720
+ }
3721
+ }
3722
+ return assignedData;
3723
+ }
3724
+
3725
+ export async function checklistAssign( req, res ) {
3726
+ try {
3727
+ if ( !req.body.checklistId ) {
3728
+ return res.sendError( 'Checklist id is required', 400 );
3729
+ }
3730
+ if ( !req.body.coverage ) {
3731
+ return res.sendError( 'Coverage is required', 400 );
3732
+ }
3733
+ if ( !req.body.idList ) {
3734
+ return res.sendError( 'Id is required', 400 );
3735
+ }
3736
+
3737
+ let checklistDetails = await checklistService.findOne( { _id: req.body.checklistId } );
3738
+ if ( !checklistDetails ) {
3739
+ return res.sendError( 'No data found', 204 );
3740
+ }
3741
+
3742
+ let uniqueArr = [];
3743
+
3744
+ await Promise.all( req.body.idList.map( async ( data ) => {
3745
+ let assignedData = {
3746
+ ...data,
3747
+ clientId: req.body.clientId,
3748
+ };
3749
+ let uploadData = await assignUsers( assignedData );
3750
+ if ( uploadData?.length ) {
3751
+ uniqueArr.push( ...uploadData );
3752
+ }
3753
+ } ) );
3754
+
3755
+ if ( uniqueArr.length ) {
3756
+ if ( req.body.coverage == 'store' ) {
3757
+ uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3758
+ if ( acc[obj.storeName] ) {
3759
+ acc[obj.storeName].clusterName += ',' + obj.clusterName;
3760
+ } else {
3761
+ acc[obj.storeName] = { ...obj };
3762
+ }
3763
+ return acc;
3764
+ }, {} );
3765
+
3766
+ uniqueArr= Object.values( uniqueArr );
3767
+ } else {
3768
+ uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3769
+ if ( acc[obj.userEmail] ) {
3770
+ acc[obj.userEmail].teamName += ','+ obj.teamName;
3771
+ } else {
3772
+ acc[obj.userEmail] = { ...obj };
3773
+ }
3774
+ return acc;
3775
+ }, {} );
3776
+ uniqueArr = Object.values( uniqueArr );
3777
+ }
3778
+ }
3779
+
3780
+ return res.sendSuccess( { count: uniqueArr.length, uniqueArr } );
3781
+ } catch ( e ) {
3782
+ logger.error( { functionName: 'checklistAssign', error: e } );
3783
+ return res.sendError( e, 500 );
3784
+ }
3785
+ }
3786
+
3787
+ export async function updateAssign( req, res ) {
3788
+ try {
3789
+ // if ( !req.body.assignedList.length && !req.body.assignedGroup.length ) {
3790
+ // return res.sendError( 'No data found', 204 );
3791
+ // }
3792
+ let checklistDetails = await checklistService.findOne( { _id: req.body.checkListId, client_id: req.body.clientId } );
3793
+ if ( !checklistDetails ) {
3794
+ return res.sendError( 'No data found', 204 );
3795
+ }
3796
+ req.body.assignedGroup = [ ...new Set( req.body.assignedGroup.map( ( item ) => item.id ) ) ];
3797
+ // req.body.assignedGroup = req.body.assignedGroup.map( ( ele ) => {
3798
+ // return { id: ele };
3799
+ // } );
3800
+ await assignedService.deleteMany( { checkListId: req.body.checkListId } );
3801
+ let assignedUserList = [];
3802
+ let userEmailList = req.body.assignedList.map( ( ele ) => ele.userEmail.toLowerCase() );
3803
+ let query = [
3804
+ {
3805
+ $addFields: {
3806
+ emailToLower: { $toLower: '$email' },
3807
+ },
3808
+ },
3809
+ {
3810
+ $match: {
3811
+ clientId: req.body.clientId,
3812
+ emailToLower: { $in: userEmailList },
3813
+ },
3814
+ },
3815
+ ];
3816
+ let assignUserDetails = await userService.aggregate( query );
3817
+ for ( let assign of req.body.assignedList ) {
3818
+ // await Promise.all( req.body.assignedList.map( async ( assign ) => {
3819
+ let userDetails = assignUserDetails.find( ( ele ) => ele.email.toLowerCase() == assign.userEmail.toLowerCase() );
3820
+ if ( !userDetails ) {
3821
+ let userData = {
3822
+ userName: assign.userName,
3823
+ email: assign.userEmail,
3824
+ mobileNumber: assign?.userPhone || '',
3825
+ clientId: req.body.clientId,
3826
+ };
3827
+ userDetails = await createUser( userData );
3828
+ userDetails = userDetails;
3829
+ }
3830
+ let data = {
3831
+ ...assign,
3832
+ userEmail: userDetails?.email,
3833
+ store_id: assign?.storeId,
3834
+ client_id: req.body.clientId,
3835
+ checkListId: req.body.checkListId,
3836
+ coverage: req.body.coverage,
3837
+ assignId: assign._id,
3838
+ userId: userDetails?._id,
3839
+ checkListName: checklistDetails.checkListName,
3840
+ };
3841
+ delete data._id;
3842
+ assignedUserList.push( data );
3843
+ // } ) );
3844
+ }
3845
+ let assignGroupDetails = [];
3846
+ if ( req.body.coverage == 'store' ) {
3847
+ assignGroupDetails = await clusterServices.findcluster( { _id: { $in: req.body.assignedGroup } } );
3848
+ } else {
3849
+ assignGroupDetails = await teamsServices.findteams( { _id: { $in: req.body.assignedGroup } } );
3850
+ }
3851
+ await Promise.all( req.body.assignedGroup.map( async ( assign ) => {
3852
+ let groupDetails = assignGroupDetails.find( ( ele ) => ele._id.toString() == assign );
3853
+ if ( groupDetails ) {
3854
+ let groupData = {
3855
+ client_id: req.body.clientId,
3856
+ checkListId: req.body.checkListId,
3857
+ coverage: req.body.coverage,
3858
+ assignId: assign,
3859
+ checkListName: checklistDetails.checkListName,
3860
+ ...( req.body.coverage == 'store' ) ? { clusterName: groupDetails?.clusterName } : { teamName: groupDetails?.teamName },
3861
+ };
3862
+ assignedUserList.push( groupData );
3863
+ }
3864
+ } ) );
3865
+ await assignedService.insertMany( assignedUserList );
3866
+ return res.sendSuccess( 'Assign details updated successfully' );
3867
+ } catch ( e ) {
3868
+ logger.error( { functionName: 'updateAssign', error: e } );
3869
+ return res.sendError( e, 500 );
3870
+ }
3871
+ }
3872
+
3873
+ export async function updateAiConfigure( req, res ) {
3874
+ try {
3875
+ if ( !req.body.storeList.length && req.body.publish ) {
3876
+ return res.sendError( 'Please assign a store', 400 );
3877
+ }
3878
+ if ( !req.body.id && !req.body.type ) {
3879
+ return res.sendError( 'Type/Id is required', 400 );
3880
+ }
3881
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'global' && !req.body?.aiConfig?.events?.length ) {
3882
+ return res.sendError( 'Event is required', 400 );
3883
+ }
3884
+ let query;
3885
+ query = req.body.type ? { checkListType: req.body.type, client_id: { $exists: false } } : { _id: req.body.id, client_id: req.body.clientId };
3886
+ let aiChecklistDetails = await checklistService.findOne( query );
3887
+ if ( !aiChecklistDetails ) {
3888
+ return res.sendError( 'No data found', 204 );
3889
+ }
3890
+ let details = {
3891
+ checkListName: aiChecklistDetails.checkListName,
3892
+ checkListDescription: aiChecklistDetails.checkListDescription,
3893
+ client_id: req.body.clientId,
3894
+ publish: req.body.publish,
3895
+ aiConfig: req.body.aiConfig,
3896
+ createdBy: req.user._id,
3897
+ createdByName: req.user.userName,
3898
+ questionCount: 0,
3899
+ storeCount: req.body.storeList.length,
3900
+ type: 'checklist',
3901
+ checkListType: aiChecklistDetails.checkListType,
3902
+ schedule: 'daily',
3903
+ ...( req.body.publish ) ? { publishDate: new Date() } :{},
3904
+ approver: req.body?.approver || [],
3905
+ scheduleRepeatedDay: [ '01' ],
3906
+ scheduleStartTime: '06:00 AM',
3907
+ scheduleEndTime: '11:59 PM',
3908
+ };
3909
+ let aiResponse = await checklistService.updateOne( { checkListType: aiChecklistDetails.checkListType, client_id: req.body.clientId }, details );
3910
+ let checklistId = req.body?.id || aiResponse?.upsertedId;
3911
+ if ( req.body.storeList ) {
3912
+ let storeData = [];
3913
+ req.body.storeList.forEach( ( ele ) => {
3914
+ let eventTime = [];
3915
+ Object.keys( ele ).forEach( ( key ) => {
3916
+ let keyValue ={};
3917
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'store' && key.includes( 'startTime' ) ) {
3918
+ let num = key.slice( -1 );
3919
+ keyValue['time'] = ele[key];
3920
+ keyValue['duration'] = ele[`configTime${num}`];
3921
+ eventTime.push( keyValue );
3922
+ }
3923
+ } );
3924
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'global' ) {
3925
+ req.body.aiConfig.events.forEach( ( event ) => {
3926
+ if ( event.time.split( ':' ).length <= 2 ) {
3927
+ event.time = event.time + ':00';
3928
+ }
3929
+ } );
3930
+ eventTime = req.body.aiConfig.events;
3931
+ }
3932
+ storeData.push( {
3933
+ storeName: ele.storeName,
3934
+ ...( req.body.aiConfig?.assignConfig ) ? { events: eventTime } : { events: [] },
3935
+ checkListId: checklistId,
3936
+ client_id: req.body.clientId,
3937
+ checkListName: aiChecklistDetails.checkListName,
3938
+ store_id: ele.storeId,
3939
+ assignId: ele._id,
3940
+ } );
3941
+ } );
3942
+ await assignedService.deleteMany( { checkListId: checklistId } );
3943
+ await assignedService.insertMany( storeData );
3944
+ if ( req.body.publish ) {
3945
+ let processedData = {
3946
+ client_id: req.body.clientId,
3947
+ date_iso: new Date( dayjs().format( 'YYYY-MM-DD' ) ),
3948
+ date_string: dayjs().format( 'YYYY-MM-DD' ),
3949
+ sourceCheckList_id: checklistId,
3950
+ checkListName: aiChecklistDetails.checkListName,
3951
+ checkListDescription: aiChecklistDetails.checkListDescription,
3952
+ scheduleStartTime: '06:00 AM',
3953
+ scheduleEndTime: '11:59 PM',
3954
+ scheduleStartTime_iso: dayjs.utc( '06:00 AM', 'hh:mm A' ).format(),
3955
+ scheduleEndTime_iso: dayjs.utc( '11:59 PM', 'hh:mm A' ).format(),
3956
+ allowedOverTime: false,
3957
+ allowedStoreLocation: false,
3958
+ createdBy: req.user._id,
3959
+ createdByName: req.user.userName,
3960
+ questionAnswers: [],
3961
+ isdeleted: false,
3962
+ questionCount: 0,
3963
+ storeCount: req.body.storeList.length,
3964
+ publishDate: details?.publishDate,
3965
+ locationCount: 1,
3966
+ checkListType: aiChecklistDetails.checkListType,
3967
+ scheduleRepeatedType: 'daily',
3968
+ aiStoreList: storeData.length? storeData.map( ( store ) => {
3969
+ return { storeName: store.storeName, events: store.events, storeId: store.store_id };
3970
+ } ) : [],
3971
+ aiConfig: req.body.aiConfig,
3972
+ approver: req.body?.approver || [],
3973
+ };
3974
+ let configResponse = await processedchecklistConfig.updateOne( { date_string: dayjs().format( 'YYYY-MM-DD' ), sourceCheckList_id: checklistId, checkListType: aiChecklistDetails.checkListType }, processedData );
3975
+ let data = {
3976
+ ...( configResponse?.upsertedId ) ? { checkListId: configResponse?.upsertedId } : {},
3977
+ checkListName: aiChecklistDetails.checkListName,
3978
+ checkListDescription: aiChecklistDetails.checkListDescription,
3979
+ date_iso: new Date( dayjs().format( 'YYYY-MM-DD' ) ),
3980
+ date_string: dayjs().format( 'YYYY-MM-DD' ),
3981
+ allowedOverTime: false,
3982
+ allowedStoreLocation: false,
3983
+ scheduleStartTime: '06:00 AM',
3984
+ scheduleStartTime_iso: dayjs.utc( '06:00 AM', 'hh:mm A' ).format(),
3985
+ scheduleEndTime: '11:59 PM',
3986
+ scheduleEndTime_iso: dayjs.utc( '11:59 PM', 'hh:mm A' ).format(),
3987
+ createdBy: req.user._id,
3988
+ createdByName: req.user.userName,
3989
+ sourceCheckList_id: checklistId,
3990
+ checkListType: aiChecklistDetails.checkListType,
3991
+ storeCount: req.body.storeList.length,
3992
+ questionCount: 0,
3993
+ publishDate: new Date(),
3994
+ locationCount: 0,
3995
+ scheduleRepeatedType: 'daily',
3996
+ client_id: req.body.clientId,
3997
+ aiStoreList: req.body.storeList ? req.body.storeList.map( ( store ) => store.store_id ) : [],
3998
+ };
3999
+ await processedchecklist.updateOne( { date_string: dayjs().format( 'YYYY-MM-DD' ), sourceCheckList_id: checklistId, checkListType: aiChecklistDetails.checkListType }, data );
4000
+ }
4001
+ }
4002
+ return res.sendSuccess( 'Checklist updated successfully' );
4003
+ } catch ( e ) {
4004
+ logger.error( { functionName: 'updateAiConfigure', error: e } );
4005
+ return res.sendError( e, 500 );
4006
+ }
4007
+ }
4008
+
4009
+
4010
+ export async function getAiDetails( req, res ) {
4011
+ try {
4012
+ let storeList = [];
4013
+ if ( !req.query.id && !req.query.type ) {
4014
+ return res.sendError( 'Type/Id is required', 400 );
4015
+ }
4016
+ let query = req.query.type ? { checkListType: req.query.type, client_id: { $exists: false } } : { _id: req.query.id, client_id: req.query.clientId };
4017
+ let checklistDetails = await checklistService.findOne( query );
4018
+ if ( !checklistDetails ) {
4019
+ return res.sendError( 'No data found', 204 );
4020
+ }
4021
+ if ( req.query?.id ) {
4022
+ storeList = await assignedService.find( { checkListId: req.query?.id } );
4023
+ let data = [];
4024
+ await Promise.all( ( storeList.map( async ( ele ) => {
4025
+ let element = {};
4026
+ element['storeName'] = ele.storeName,
4027
+ element['storeId'] = ele.store_id;
4028
+ element['_id'] = ele.assignId;
4029
+ let getStoreDetails = await storeService.findOne( { storeId: ele.store_id, status: 'active', clientId: req.query.clientId } );
4030
+ if ( getStoreDetails ) {
4031
+ element['openTime'] = getStoreDetails?.storeProfile?.open;
4032
+ element['closeTime'] = getStoreDetails?.storeProfile?.close;
4033
+ }
4034
+ if ( [ 'cleaning', 'scrum' ].includes( checklistDetails.checkListType ) && checklistDetails?.aiConfig?.assignConfig == 'store' ) {
4035
+ ele.events.forEach( ( event, index ) => {
4036
+ element[`startTime${index+1}`] = event.time;
4037
+ element[`configTime${index+1}`] = event.duration;
4038
+ } );
4039
+ }
4040
+ data.push( element );
4041
+ } ) ) );
4042
+ storeList = data;
4043
+ }
4044
+
4045
+ let response = {
4046
+ checkListName: checklistDetails?.checkListName,
4047
+ checkListDescription: checklistDetails?.checkListDescription,
4048
+ publish: checklistDetails?.publish,
4049
+ aiConfig: checklistDetails?.aiConfig,
4050
+ storeList: storeList,
4051
+ approver: checklistDetails?.approver,
4052
+ storeCount: checklistDetails?.storeCount,
4053
+ ...( checklistDetails?.client_id ) ? { clientId: checklistDetails?.client_id } :{},
4054
+ enableNewDeployedStore: checklistDetails?.enableNewDeployedStore,
4055
+ };
4056
+ return res.sendSuccess( response );
4057
+ } catch ( e ) {
4058
+ logger.error( { functionName: getAiDetails, error: e } );
4059
+ return res.sendError( e, 500 );
4060
+ }
4061
+ }