tango-app-api-trax 3.2.1 → 3.3.1-airtel-1

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,6 +1412,220 @@ export const updateConfigure =async ( req, res ) => {
1242
1412
  }
1243
1413
  };
1244
1414
 
1415
+ export const updateConfigurev1 =async ( req, res ) => {
1416
+ try {
1417
+ let inputBody = req.body;
1418
+ let id;
1419
+ let checklistDetails;
1420
+ if ( !inputBody.checkListDetails._id ) {
1421
+ return res.sendError( 'checkListId is Required', 400 );
1422
+ }
1423
+
1424
+ if ( inputBody.checkListDetails.checkListType == 'mobileusagedetection' && inputBody.submitType == 'publish' ) {
1425
+ if ( !inputBody?.checkListDetails?.alert?.usageExceeds ) {
1426
+ return res.sendError( 'Please Enter usage exceeds', 400 );
1427
+ }
1428
+
1429
+ if ( !inputBody?.checkListDetails?.alert?.alertsTo.length ) {
1430
+ return res.sendError( 'Please select users to send alert', 400 );
1431
+ }
1432
+
1433
+ if ( !inputBody?.checkListDetails?.detectionArea.length ) {
1434
+ return res.sendError( 'Please select detection area', 400 );
1435
+ }
1436
+ }
1437
+
1438
+ if ( !inputBody.checkListDetails.assignedUsers.length && inputBody.submitType == 'publish' ) {
1439
+ return res.sendError( 'Please Assigned a user', 400 );
1440
+ }
1441
+
1442
+ if ( !inputBody?.checkListDetails?.approver.length && inputBody.submitType == 'publish' ) {
1443
+ return res.sendError( 'Please assign approver', 400 );
1444
+ }
1445
+
1446
+
1447
+ let logInsertData = {
1448
+ action: inputBody.submitType == 'publish' ? 'checklistPublishUsingConfigPage' : 'checklistConfigDraft',
1449
+ checklistId: inputBody.checkListDetails._id,
1450
+ checkListName: inputBody?.checkListDetails.checkListName,
1451
+ createdBy: req.user._id,
1452
+ createdByName: req.user.userName,
1453
+ client_id: req.body.clientId,
1454
+ createdByEmail: req.user.email,
1455
+ approver: inputBody?.checkListDetails?.approver || [],
1456
+ };
1457
+ await checklistLogs.create( logInsertData );
1458
+
1459
+ checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist', isdeleted: false } );
1460
+
1461
+ if ( [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection' ].includes( inputBody.checkListDetails.checkListType ) && inputBody.uploadUser ) {
1462
+ checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist' } );
1463
+ }
1464
+
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();
1477
+
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
+
1245
1629
  export const updatePublish = async ( req, res ) => {
1246
1630
  try {
1247
1631
  if ( typeof req?.body?.checklistId == 'undefined' && typeof req.body.type == 'undefined' ) {
@@ -1570,6 +1954,233 @@ export const validateUser = async ( req, res ) => {
1570
1954
  }
1571
1955
  };
1572
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.toLowerCase() == item.storeName.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;
2111
+ }
2112
+ } );
2113
+ }
2114
+
2115
+ if ( ( newUserList.length || newStoreList.length || existEmail.length || inActiveStores.length ) && !req.body?.addUser ) {
2116
+ return res.sendError( { validate: false, user: newUserList, store: newStoreList, existEmail, inActiveStores, data: assignDetails }, 400 );
2117
+ }
2118
+ await Promise.all( newUserList.map( async ( ele ) => {
2119
+ let findUserIndex = assignDetails.findIndex( ( item ) => item?.userEmail?.toLowerCase() == ele?.toLowerCase() );
2120
+ if ( findUserIndex != -1 ) {
2121
+ let data = {
2122
+ userName: assignDetails[findUserIndex]?.userName,
2123
+ email: ele,
2124
+ mobileNumber: assignDetails[findUserIndex]?.mobileNumber,
2125
+ clientId: req.body.clientId,
2126
+ };
2127
+ let response = await createUser( data );
2128
+ if ( req.body.coverage == 'user' ) {
2129
+ assignDetails[findUserIndex]._id = response._id;
2130
+ }
2131
+ }
2132
+ } ) );
2133
+ return res.sendSuccess( { validate: true, data: assignDetails } );
2134
+ } catch ( e ) {
2135
+ logger.error( 'validateUser 2=>', e );
2136
+ return res.sendError( e, 500 );
2137
+ }
2138
+ };
2139
+
2140
+ // export async function assignChecklistUser( req, res ) {
2141
+ // try {
2142
+ // let inputBody = req.body;
2143
+ // let assignDetails = inputBody.assignUsers;
2144
+ // let newUsers = inputBody.newUsers;
2145
+ // let checklistDetails = await checklistService.findOne( { _id: inputBody.checklistId } );
2146
+ // if ( !checklistDetails ) {
2147
+ // return res.sendError( 'No data found', 204 );
2148
+ // }
2149
+ // await Promise.all( newUsers.map( async ( user ) => {
2150
+ // let getUser = inputBody.assignUsers.find( ( ele ) => ele.userEmail.toLowerCase() == user.toLowerCase() );
2151
+ // let userData = {
2152
+ // userName: getUser.userName,
2153
+ // email: user,
2154
+ // mobileNumber: getUser?.phone,
2155
+ // clientId: inputBody.clientId,
2156
+ // };
2157
+ // await createUser( userData );
2158
+ // } ) );
2159
+ // let assignData = [];
2160
+ // await Promise.all( assignDetails.map( async ( assign ) => {
2161
+ // assign.checklistId = inputBody.taskId;
2162
+ // assign.checkListName = checklistDetails.checkListName;
2163
+ // assign.coverage = inputBody.coverage;
2164
+ // assign.clientId = inputBody.clientId;
2165
+ // assign.upload = inputBody.type;
2166
+ // let uploadData = await assignUsers( assign );
2167
+ // if ( uploadData ) {
2168
+ // if ( Array.isArray( uploadData ) ) {
2169
+ // assignData.push( ...uploadData );
2170
+ // } else {
2171
+ // assignData.push( uploadData );
2172
+ // }
2173
+ // }
2174
+ // } ) );
2175
+ // return res.sendSuccess( { idList: [ ...new Set( assignData.map( ( item ) => {
2176
+ // return { id: item?.assignId?.toString(), type: inputBody.coverage == 'store' ? typeof item.clusterName == 'undefined' ? 'store' : 'cluster' : typeof item.teamsName == 'undefined' ? 'user' : 'teams' };
2177
+ // } ) ) ], assignData } );
2178
+ // } catch ( e ) {
2179
+ // logger.error( { functionName: 'assignUser', error: e } );
2180
+ // return res.sendError( e, 500 );
2181
+ // }
2182
+ // }
2183
+
1573
2184
  async function uploadUser( req, res ) {
1574
2185
  try {
1575
2186
  let inputBody = req.body;
@@ -1944,6 +2555,8 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1944
2555
  insertdata.approver = getCLconfig?.approver || [];
1945
2556
  insertdata.remainder = getCLconfig?.remainder || [];
1946
2557
  insertdata.restrictAttendance = getCLconfig?.restrictAttendance;
2558
+ insertdata.coverage = getCLconfig?.coverage;
2559
+ insertdata.rawImageUpload = getCLconfig?.rawImageUpload || false;
1947
2560
 
1948
2561
  let collectSections = [];
1949
2562
  let sectionQuery = [];
@@ -1981,7 +2594,7 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1981
2594
  updatedchecklist = checklistDetails;
1982
2595
  }
1983
2596
  if ( updatedchecklist ) {
1984
- insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit );
2597
+ insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit );
1985
2598
  }
1986
2599
  }
1987
2600
  }
@@ -1992,7 +2605,322 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
1992
2605
  }
1993
2606
  };
1994
2607
 
1995
- async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
2608
+ // async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
2609
+ // let getquestionQuery = [];
2610
+ // if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection' ].includes( getCLconfig.checkListType ) ) {
2611
+ // getquestionQuery.push(
2612
+ // {
2613
+ // $match: {
2614
+ // checkListId: new ObjectId( checklistId ),
2615
+ // checkFlag: true,
2616
+ // },
2617
+ // },
2618
+ // {
2619
+ // $group: {
2620
+ // '_id': '$store_id',
2621
+ // 'store_id': { $first: '$store_id' },
2622
+ // 'client_id': { $first: '$client_id' },
2623
+ // 'storeName': { $first: '$storeName' },
2624
+ // 'userId': { $first: '$userId' },
2625
+ // 'userEmail': { $first: '$userEmail' },
2626
+ // 'userName': { $first: '$userName' },
2627
+ // 'checkFlag': { $first: '$checkFlag' },
2628
+ // 'checkListId': { $first: '$checkListId' },
2629
+ // 'checkListName': { $first: '$checkListName' },
2630
+ // 'country': { $first: '$country' },
2631
+ // 'createdAt': { $first: '$createdAt' },
2632
+ // 'updatedAt': { $first: '$updatedAt' },
2633
+ // },
2634
+ // },
2635
+ // );
2636
+ // } else {
2637
+ // getquestionQuery.push( {
2638
+ // $match: {
2639
+ // checkListId: new ObjectId( checklistId ),
2640
+ // checkFlag: true,
2641
+ // isdeleted: false,
2642
+ // },
2643
+ // } );
2644
+ // }
2645
+ // let allQuestion = await assignedService.aggregate( getquestionQuery );
2646
+ // if ( allQuestion ) {
2647
+ // let userIdList = [];
2648
+ // let tokenList = [];
2649
+ // let notifyUserList = [];
2650
+ // let status = [ { checklistStatus: { $ne: 'open' } } ];
2651
+
2652
+ // for ( let element4 of allQuestion ) {
2653
+ // let getToken = await userService.findOne( { _id: element4.userId }, { fcmToken: 1 } );
2654
+ // if ( getToken && getToken?.fcmToken && element4?.sendNotification && showEdit ) {
2655
+ // tokenList.push( getToken.fcmToken );
2656
+ // }
2657
+ // if ( !element4?.sendNotification ) {
2658
+ // notifyUserList.push( { token: getToken?.fcmToken, storeName: element4.storeName, id: element4._id } );
2659
+ // }
2660
+ // if ( !getCLconfig?.allowedMultiSubmit ) {
2661
+ // let query;
2662
+ // if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
2663
+ // if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
2664
+ // let startDate; let endDate;
2665
+ // if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
2666
+ // startDate = dayjs.utc( date ).clone().startOf( 'week' );
2667
+ // endDate = dayjs.utc( date ).clone().endOf( 'week' );
2668
+ // } else {
2669
+ // startDate = dayjs.utc( date ).clone().startOf( 'month' );
2670
+ // endDate = dayjs.utc( date ).clone().endOf( 'month' );
2671
+ // }
2672
+ // query = {
2673
+ // sourceCheckList_id: getCLconfig._id,
2674
+ // $or: [
2675
+ // { submitTime: { $exists: true } },
2676
+ // ...status,
2677
+ // ],
2678
+ // userId: element4.userId,
2679
+ // store_id: element4.store_id,
2680
+ // $and: [ {
2681
+ // date_iso: {
2682
+ // $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
2683
+ // $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
2684
+ // } ],
2685
+ // };
2686
+ // } else {
2687
+ // if ( getCLconfig.schedule == 'range' ) {
2688
+ // query = {
2689
+ // sourceCheckList_id: getCLconfig._id,
2690
+ // $or: [
2691
+ // { submitTime: { $exists: true } },
2692
+ // ...status,
2693
+ // ],
2694
+ // userId: element4.userId,
2695
+ // store_id: element4.store_id,
2696
+ // $and: [
2697
+ // {
2698
+ // date_iso: {
2699
+ // $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
2700
+ // $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ),
2701
+ // },
2702
+ // },
2703
+ // ],
2704
+ // };
2705
+ // }
2706
+ // }
2707
+ // } else {
2708
+ // query = {
2709
+ // date_string: date,
2710
+ // sourceCheckList_id: getCLconfig._id,
2711
+ // $or: [
2712
+ // ...status,
2713
+ // { submitTime: { $exists: true } },
2714
+ // ],
2715
+ // userId: element4.userId,
2716
+ // store_id: element4.store_id,
2717
+ // };
2718
+ // }
2719
+ // let getsubmitDetails = await processedchecklist.find( query );
2720
+ // function findDifferences( obj1, obj2 ) {
2721
+ // return Object.keys( obj1 ).reduce( ( diff, key ) => {
2722
+ // if ( !isEqual( obj1[key], obj2[key] ) ) {
2723
+ // diff[key] = { value1: obj1[key], value2: obj2[key] };
2724
+ // }
2725
+ // return diff;
2726
+ // }, {} );
2727
+ // }
2728
+ // if ( getsubmitDetails.length ) {
2729
+ // if ( showEdit && ( ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) || getsubmitDetails[0].checklistStatus == 'inprogress' ) ) {
2730
+ // let modifiedCount = 0;
2731
+ // let questionList = insertdata.questionAnswers;
2732
+ // if ( getsubmitDetails[0].checkListName != getCLconfig.checkListName ) {
2733
+ // getsubmitDetails[0].checkListName = getCLconfig.checkListName;
2734
+ // }
2735
+ // if ( getsubmitDetails[0].checkListDescription != getCLconfig.checkListDescription ) {
2736
+ // getsubmitDetails[0].checkListDescription = getCLconfig.checkListDescription;
2737
+ // }
2738
+ // let sectionList = [];
2739
+ // for ( let [ index, section ] of questionList.entries() ) {
2740
+ // let checkExists = getsubmitDetails[0].questionAnswers.findIndex( ( sec ) => sec.sectionName == section?.sectionOldName || sec.sectionName == section.sectionName );
2741
+ // if ( checkExists != -1 ) {
2742
+ // getsubmitDetails[0].questionAnswers[index].section_id = section.section_id;
2743
+ // getsubmitDetails[0].questionAnswers[index].sectionName = section.sectionName;
2744
+ // let question = [];
2745
+ // section.questions.forEach( ( qns ) => {
2746
+ // let findQuestion = getsubmitDetails[0].questionAnswers[index].questions.findIndex( ( ele ) => ele.qname.trim() == qns?.oldQname?.trim() || ele.qname.trim() == qns.qname.trim() );
2747
+ // if ( findQuestion != -1 ) {
2748
+ // let data = JSON.parse( JSON.stringify( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] ) );
2749
+ // getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qno = qns.qno;
2750
+ // delete data.userAnswer;
2751
+ // delete data.parentanswer;
2752
+ // delete data.remarks;
2753
+ // delete data.linkquestionenabled;
2754
+ // if ( data.descriptivetype == null ) {
2755
+ // delete data.descriptivetype;
2756
+ // }
2757
+ // qns.answers.forEach( ( ans ) => {
2758
+ // delete ans.validationAnswer;
2759
+ // delete ans.answeroptionNumber;
2760
+ // } );
2761
+ // data.answers.forEach( ( ans ) => {
2762
+ // delete ans.index;
2763
+ // delete ans.validationAnswer;
2764
+ // delete ans.answeroptionNumber;
2765
+ // } );
2766
+ // const compare = findDifferences( data, qns );
2767
+ // if ( compare?.answerType || compare?.answers || compare?.linkType ) {
2768
+ // logger.info( 'compare =>', compare );
2769
+ // modifiedCount++;
2770
+ // question.push( qns );
2771
+ // } else {
2772
+ // getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qname = qns.qname;
2773
+ // question.push( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] );
2774
+ // }
2775
+ // } else {
2776
+ // modifiedCount++;
2777
+ // question.push( qns );
2778
+ // }
2779
+ // } );
2780
+ // getsubmitDetails[0].questionAnswers[index].questions = question;
2781
+ // sectionList.push( getsubmitDetails[0].questionAnswers[index] );
2782
+ // } else {
2783
+ // modifiedCount++;
2784
+ // sectionList.push( section );
2785
+ // }
2786
+ // }
2787
+ // getsubmitDetails[0].questionAnswers = sectionList;
2788
+ // if ( modifiedCount ) {
2789
+ // getsubmitDetails[0].checklistStatus = 'inprogress';
2790
+ // getsubmitDetails[0].date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
2791
+ // getsubmitDetails[0].date_iso = new Date( date );
2792
+ // getsubmitDetails[0].redoStatus = false;
2793
+ // getsubmitDetails[0].approvalStatus = false;
2794
+ // }
2795
+ // let data = { ...getsubmitDetails[0]._doc };
2796
+ // await processedchecklist.updateOne( { _id: getsubmitDetails[0]._id }, data );
2797
+ // if ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) {
2798
+ // console.log( editSubmit );
2799
+ // let user = {
2800
+ // _id: getsubmitDetails[0].userId,
2801
+ // clientId: getsubmitDetails[0].client_id,
2802
+ // };
2803
+ // updateOpenSearch( user, { processedcheckListId: getsubmitDetails[0]._id, date: getsubmitDetails[0].date_string } );
2804
+ // }
2805
+ // }
2806
+ // if ( getsubmitDetails[0]?.checklistStatus == 'submit' ) {
2807
+ // userIdList.push( element4._id );
2808
+ // continue;
2809
+ // }
2810
+ // }
2811
+ // }
2812
+ // delete element4._id;
2813
+ // delete element4.checkFlag;
2814
+ // delete element4.isdeleted;
2815
+ // delete element4.createdAt;
2816
+ // delete element4.updatedAt;
2817
+ // element4.checkListId = updatedchecklist._id;
2818
+ // element4.checkListName = getCLconfig.checkListName;
2819
+ // element4.checkListDescription = getCLconfig.checkListDescription;
2820
+ // element4.date_iso = new Date( date );
2821
+ // element4.date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
2822
+ // element4.allowedOverTime = getCLconfig.allowedOverTime;
2823
+ // element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
2824
+ // element4.scheduleStartTime = getCLconfig.scheduleStartTime;
2825
+ // element4.scheduleStartTime_iso = startTimeIso.format();
2826
+ // element4.scheduleEndTime = getCLconfig.scheduleEndTime;
2827
+ // element4.scheduleEndTime_iso = endTimeIso.format();
2828
+ // element4.createdBy = new ObjectId( getCLconfig.createdBy );
2829
+ // element4.createdByName = getCLconfig.createdByName;
2830
+ // element4.sourceCheckList_id = getCLconfig._id;
2831
+ // element4.checkListType = getCLconfig.checkListType;
2832
+ // element4.storeCount = getCLconfig.storeCount;
2833
+ // element4.questionCount = getCLconfig.questionCount;
2834
+ // element4.publishDate = getCLconfig.publishDate;
2835
+ // element4.locationCount = getCLconfig.locationCount;
2836
+ // element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
2837
+ // element4.approvalEnable = getCLconfig.approver.length ? true : false;
2838
+ // element4.remainder = getCLconfig?.remainder || [];
2839
+ // element4.restrictAttendance = getCLconfig?.restrictAttendance;
2840
+ // }
2841
+ // if ( userIdList.length ) {
2842
+ // allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
2843
+ // }
2844
+ // if ( allQuestion ) {
2845
+ // if ( getCLconfig?.allowedMultiSubmit || processId ) {
2846
+ // if ( processId ) {
2847
+ // let processedDetails = await processedchecklist.findOne( { _id: processId } );
2848
+ // if ( processedDetails ) {
2849
+ // let submitUser = allQuestion.find( ( item ) => item.userId.toString() == processedDetails.userId.toString() && item.store_id == processedDetails.store_id );
2850
+ // await processedchecklist.insertMany( submitUser );
2851
+ // }
2852
+ // } else {
2853
+ // let deleteInprogressQuery = {
2854
+ // date_string: insertdata.date_string,
2855
+ // date_iso: insertdata.date_iso,
2856
+ // client_id: insertdata.client_id,
2857
+ // checkListId: updatedchecklist._id,
2858
+ // checklistStatus: { $nin: [ 'submit', 'inprogress' ] },
2859
+ // redoStatus: false,
2860
+ // };
2861
+ // await processedchecklist.deleteMany( deleteInprogressQuery );
2862
+ // deleteInprogressQuery.checklistStatus = 'inprogress';
2863
+ // deleteInprogressQuery.redoStatus = false;
2864
+ // let getInprogressData = await processedchecklist.find( deleteInprogressQuery, { userId: 1, store_id: 1 } );
2865
+ // if ( getInprogressData ) {
2866
+ // allQuestion = allQuestion.filter( ( item ) => {
2867
+ // let inprogressData = getInprogressData.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
2868
+ // if ( !inprogressData ) {
2869
+ // return item;
2870
+ // }
2871
+ // } );
2872
+ // }
2873
+ // if ( allQuestion.length ) {
2874
+ // await processedchecklist.insertMany( allQuestion );
2875
+ // }
2876
+ // }
2877
+ // } else {
2878
+ // let unAssignedList = allQuestion.reduce( ( acc, item ) => {
2879
+ // if ( !acc[item.userEmail] ) {
2880
+ // acc[item.userEmail]=[ item.store_id ];
2881
+ // } else {
2882
+ // acc[item.userEmail].push( item.store_id );
2883
+ // }
2884
+ // return acc;
2885
+ // }, {} );
2886
+
2887
+ // let userList = Object.keys( unAssignedList );
2888
+
2889
+ // 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' ] } } );
2890
+
2891
+ // for ( let key in unAssignedList ) {
2892
+ // if ( unAssignedList.hasOwnProperty( key ) ) {
2893
+ // 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' ] } } );
2894
+ // }
2895
+ // }
2896
+
2897
+
2898
+ // Promise.all( allQuestion.map( async ( ele ) => {
2899
+ // 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 );
2900
+ // } ) );
2901
+ // }
2902
+
2903
+ // tokenList.forEach( ( item ) => {
2904
+ // const title = `${getCLconfig.checkListName}`;
2905
+ // const description = `Checklist has been updated and re-published!`;
2906
+ // const fcmToken = item;
2907
+ // sendPushNotification( title, description, fcmToken );
2908
+ // } );
2909
+
2910
+ // notifyUserList.forEach( ( item ) => {
2911
+ // const title = `New Checklist Assigned ${item.storeName}`;
2912
+ // const description = `The ${getCLconfig.checkListName} checklist has been assigned to ${item.storeName} for the first time.complete to avoid compliance.`;
2913
+ // const fcmToken = item.token;
2914
+ // sendPushNotification( title, description, fcmToken );
2915
+ // } );
2916
+
2917
+ // let updateUserList = notifyUserList.map( ( ele ) => ele.id );
2918
+ // await assignedService.updateMany( { _id: { $in: updateUserList } }, { sendNotification: true } );
2919
+ // }
2920
+ // }
2921
+ // }
2922
+
2923
+ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedchecklist, date, startTimeIso, endTimeIso, insertdata, processId, oldData, editSubmit, showEdit ) {
1996
2924
  let getquestionQuery = [];
1997
2925
  if ( [ 'storeopenandclose', 'mobileusagedetection', 'uniformdetection' ].includes( getCLconfig.checkListType ) ) {
1998
2926
  getquestionQuery.push(
@@ -2024,86 +2952,202 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2024
2952
  getquestionQuery.push( {
2025
2953
  $match: {
2026
2954
  checkListId: new ObjectId( checklistId ),
2027
- checkFlag: true,
2028
2955
  isdeleted: false,
2029
2956
  },
2030
2957
  } );
2031
2958
  }
2032
2959
  let allQuestion = await assignedService.aggregate( getquestionQuery );
2033
2960
  if ( allQuestion ) {
2961
+ let assignList = [];
2962
+ if ( getCLconfig.coverage == 'store' ) {
2963
+ let clusterList = allQuestion.filter( ( ele ) => ele?.clusterName ).map( ( item ) => item.assignId );
2964
+ if ( clusterList.length ) {
2965
+ let clusterDetails = await clusterServices.findcluster( { _id: { $in: clusterList } } );
2966
+ if ( clusterDetails.length ) {
2967
+ let idList = clusterDetails.flatMap( ( item ) => item.stores.map( ( ele ) => ele.store ) );
2968
+ let getStoreDetails = await storeService.find( { _id: { $in: idList }, status: 'active' } );
2969
+ if ( getStoreDetails.length ) {
2970
+ getStoreDetails = getStoreDetails.filter( ( store ) => {
2971
+ let findStore = allQuestion.find( ( storeList ) => storeList.assignId.toString() == store._id.toString() );
2972
+ if ( findStore ) {
2973
+ return store?.spocDetails?.[0]?.email.toLowerCase() != findStore.userEmail.toLowerCase();
2974
+ } else {
2975
+ return true;
2976
+ }
2977
+ } );
2978
+ assignList = await Promise.all( getStoreDetails.map( async ( store ) => {
2979
+ let userQuery = [
2980
+ {
2981
+ $project: {
2982
+ newEmail: { $toLower: '$email' },
2983
+ isActive: 1,
2984
+ clientId: 1,
2985
+ userName: 1,
2986
+ email: 1,
2987
+ },
2988
+ },
2989
+ {
2990
+ $match: {
2991
+ newEmail: store?.spocDetails?.[0]?.email.toLowerCase(),
2992
+ isActive: true,
2993
+ clientId: store.clientId,
2994
+ },
2995
+ },
2996
+ ];
2997
+ let userDetails = await userService.aggregate( userQuery );
2998
+ if ( !userDetails.length ) {
2999
+ let data = {
3000
+ clientId: store.clientId,
3001
+ userName: store.spocDetails?.[0]?.name,
3002
+ mobileNumber: store.spocDetails?.[0]?.phone || '',
3003
+ email: store.spocDetails[0].email,
3004
+ };
3005
+ userDetails = await createUser( data );
3006
+ userDetails = [ userDetails ];
3007
+ }
3008
+ let data = {
3009
+ store_id: store?.storeId,
3010
+ storeName: store?.storeName,
3011
+ userId: userDetails?.[0]?._id,
3012
+ userName: userDetails?.[0]?.userName,
3013
+ userEmail: userDetails?.[0]?.email,
3014
+ userPhone: userDetails?.[0]?.mobileNumber,
3015
+ city: store?.storeProfile?.city,
3016
+ country: store?.storeProfile?.country,
3017
+ checkFlag: true,
3018
+ checkListId: getCLconfig._id,
3019
+ checkListName: getCLconfig.checkListName,
3020
+ client_id: getCLconfig.client_id,
3021
+ };
3022
+ return data;
3023
+ } ) );
3024
+ }
3025
+ }
3026
+ }
3027
+ allQuestion = allQuestion.filter( ( ele ) => !clusterList.includes( ele.assignId ) );
3028
+ }
3029
+ if ( getCLconfig.coverage == 'user' ) {
3030
+ let teamsList = allQuestion.filter( ( ele ) => ele?.teamName ).map( ( item ) => item.assignId );
3031
+ if ( teamsList.length ) {
3032
+ let teamDetails = await teamsServices.findteams( { _id: { $in: teamsList } } );
3033
+ if ( teamDetails.length ) {
3034
+ let idList = [ ...teamDetails.flatMap( ( item ) => item.users.map( ( ele ) => ele.userId ) ), ...teamDetails.flatMap( ( item ) => item.Teamlead.map( ( ele ) => ele.userId ) ) ];
3035
+ let userIdList = allQuestion.filter( ( qn ) => !qn?.teamName ).map( ( qn ) => qn.assignId.toString() );
3036
+ idList = idList.filter( ( id ) => !userIdList.includes( id.toString() ) );
3037
+ let getUserDetails = await userService.find( { _id: { $in: idList } } );
3038
+ if ( getUserDetails.length ) {
3039
+ assignList = getUserDetails.map( ( user ) => {
3040
+ let data = {
3041
+ store_id: '',
3042
+ storeName: '',
3043
+ userId: user._id,
3044
+ userName: user.userName,
3045
+ userEmail: user.email,
3046
+ userPhone: user?.mobileNumber,
3047
+ city: '',
3048
+ country: '',
3049
+ checkFlag: true,
3050
+ checkListId: getCLconfig._id,
3051
+ checkListName: getCLconfig.checkListName,
3052
+ client_id: getCLconfig.client_id,
3053
+ };
3054
+ return data;
3055
+ } );
3056
+ }
3057
+ }
3058
+ }
3059
+ allQuestion = allQuestion.filter( ( ele ) => !teamsList.includes( ele.assignId ) );
3060
+ }
3061
+ allQuestion = [ ...allQuestion, ...assignList ];
2034
3062
  let userIdList = [];
2035
3063
  let tokenList = [];
2036
3064
  let notifyUserList = [];
2037
3065
  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
- }
3066
+ let assignUserList = [];
3067
+ let userList = allQuestion.map( ( item ) => item.userId );
3068
+ let submittedDetails = [];
3069
+ let userDetails = await userService.find( { _id: { $in: userList } }, { fcmToken: 1 } );
3070
+ userDetails = new Map( userDetails.map( ( ele ) => [ ele._id.toString(), ele.fcmToken ] ) );
3071
+ if ( !getCLconfig?.allowedMultiSubmit ) {
3072
+ let query;
3073
+ if ( getCLconfig.allowOnce && ![ 'onetime', 'daily' ].includes( getCLconfig.schedule ) ) {
3074
+ if ( [ 'weekday', 'weekly', 'monthly' ].includes( getCLconfig.schedule ) ) {
3075
+ let startDate; let endDate;
3076
+ if ( [ 'weekday', 'weekly' ].includes( getCLconfig.schedule ) ) {
3077
+ startDate = dayjs.utc( date ).clone().startOf( 'week' );
3078
+ endDate = dayjs.utc( date ).clone().endOf( 'week' );
3079
+ } else {
3080
+ startDate = dayjs.utc( date ).clone().startOf( 'month' );
3081
+ endDate = dayjs.utc( date ).clone().endOf( 'month' );
3082
+ }
3083
+ query = {
3084
+ sourceCheckList_id: getCLconfig._id,
3085
+ $or: [
3086
+ { submitTime: { $exists: true } },
3087
+ ...status,
3088
+ ],
3089
+ // userId: { $in: userList },
3090
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3091
+ $and: [ {
3092
+ date_iso: {
3093
+ $gte: new Date( startDate.format( 'YYYY-MM-DD' ) ),
3094
+ $lte: new Date( endDate.format( 'YYYY-MM-DD' ) ) },
3095
+ } ],
3096
+ };
3097
+ } else {
3098
+ if ( getCLconfig.schedule == 'range' ) {
2059
3099
  query = {
2060
3100
  sourceCheckList_id: getCLconfig._id,
2061
3101
  $or: [
2062
3102
  { submitTime: { $exists: true } },
2063
3103
  ...status,
2064
3104
  ],
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
- },
3105
+ // userId: element4.userId,
3106
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3107
+ $and: [
3108
+ {
3109
+ date_iso: {
3110
+ $gte: new Date( dayjs( getCLconfig.configStartDate ).format( 'YYYY-MM-DD' ) ),
3111
+ $lte: new Date( dayjs( getCLconfig.configEndDate ).format( 'YYYY-MM-DD' ) ),
2089
3112
  },
2090
- ],
2091
- };
2092
- }
3113
+ },
3114
+ ],
3115
+ };
2093
3116
  }
3117
+ }
3118
+ } else {
3119
+ query = {
3120
+ date_string: date,
3121
+ sourceCheckList_id: getCLconfig._id,
3122
+ $or: [
3123
+ ...status,
3124
+ { submitTime: { $exists: true } },
3125
+ ],
3126
+ // userId: element4.userId,
3127
+ // ...( getCLconfig.coverage == 'store' ) ? { store_id: element4.store_id }:{},
3128
+ };
3129
+ }
3130
+ submittedDetails = await processedchecklist.find( query );
3131
+ }
3132
+ await Promise.all( allQuestion.map( async ( element4 ) => {
3133
+ let getToken = userDetails.get( element4.userId.toString() );
3134
+ if ( getToken && element4?.sendNotification && showEdit ) {
3135
+ tokenList.push( getToken );
3136
+ }
3137
+ if ( !element4?.sendNotification ) {
3138
+ notifyUserList.push( { token: getToken, storeName: element4.storeName, id: element4._id } );
3139
+ }
3140
+ if ( !getCLconfig?.allowedMultiSubmit ) {
3141
+ let getsubmitDetails;
3142
+ if ( getCLconfig.coverage == 'store' ) {
3143
+ getsubmitDetails = submittedDetails.find( ( checklist ) => checklist.userId.toString() == element4.userId.toString() && checklist.store_id == element4.store_id );
2094
3144
  } 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
- };
3145
+ getsubmitDetails = submittedDetails.find( ( checklist ) => checklist.userId.toString() == element4.userId.toString() );
3146
+ }
3147
+ if ( getsubmitDetails ) {
3148
+ getsubmitDetails = [ getsubmitDetails ];
3149
+ console.log( submittedDetails, getsubmitDetails );
2105
3150
  }
2106
- let getsubmitDetails = await processedchecklist.find( query );
2107
3151
  function findDifferences( obj1, obj2 ) {
2108
3152
  return Object.keys( obj1 ).reduce( ( diff, key ) => {
2109
3153
  if ( !isEqual( obj1[key], obj2[key] ) ) {
@@ -2112,7 +3156,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2112
3156
  return diff;
2113
3157
  }, {} );
2114
3158
  }
2115
- if ( getsubmitDetails.length ) {
3159
+ if ( getsubmitDetails?.length ) {
2116
3160
  if ( showEdit && ( ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) || getsubmitDetails[0].checklistStatus == 'inprogress' ) ) {
2117
3161
  let modifiedCount = 0;
2118
3162
  let questionList = insertdata.questionAnswers;
@@ -2133,6 +3177,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2133
3177
  let findQuestion = getsubmitDetails[0].questionAnswers[index].questions.findIndex( ( ele ) => ele.qname.trim() == qns?.oldQname?.trim() || ele.qname.trim() == qns.qname.trim() );
2134
3178
  if ( findQuestion != -1 ) {
2135
3179
  let data = JSON.parse( JSON.stringify( getsubmitDetails[0].questionAnswers[index].questions[findQuestion] ) );
3180
+ getsubmitDetails[0].questionAnswers[index].questions[findQuestion].qno = qns.qno;
2136
3181
  delete data.userAnswer;
2137
3182
  delete data.parentanswer;
2138
3183
  delete data.remarks;
@@ -2177,78 +3222,95 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2177
3222
  getsubmitDetails[0].date_iso = new Date( date );
2178
3223
  getsubmitDetails[0].redoStatus = false;
2179
3224
  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
3225
  }
2190
3226
  let data = { ...getsubmitDetails[0]._doc };
2191
3227
  await processedchecklist.updateOne( { _id: getsubmitDetails[0]._id }, data );
3228
+ if ( editSubmit && getsubmitDetails[0].checklistStatus == 'submit' ) {
3229
+ let user = {
3230
+ _id: getsubmitDetails[0].userId,
3231
+ clientId: getsubmitDetails[0].client_id,
3232
+ };
3233
+ updateOpenSearch( user, { processedcheckListId: getsubmitDetails[0]._id, date: getsubmitDetails[0].date_string } );
3234
+ }
2192
3235
  }
2193
3236
  if ( getsubmitDetails[0]?.checklistStatus == 'submit' ) {
2194
3237
  userIdList.push( element4._id );
2195
- continue;
2196
3238
  }
2197
3239
  }
2198
3240
  }
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
- }
3241
+ if ( !userIdList.includes( element4._id ) ) {
3242
+ delete element4._id;
3243
+ delete element4.checkFlag;
3244
+ delete element4.isdeleted;
3245
+ delete element4.createdAt;
3246
+ delete element4.updatedAt;
3247
+ element4.checkListId = updatedchecklist._id;
3248
+ element4.checkListName = getCLconfig.checkListName;
3249
+ element4.checkListDescription = getCLconfig.checkListDescription;
3250
+ element4.date_iso = new Date( date );
3251
+ element4.date_string = dayjs( currentdate ).format( 'YYYY-MM-DD' );
3252
+ element4.allowedOverTime = getCLconfig.allowedOverTime;
3253
+ element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
3254
+ element4.scheduleStartTime = getCLconfig.scheduleStartTime;
3255
+ element4.scheduleStartTime_iso = startTimeIso.format();
3256
+ element4.scheduleEndTime = getCLconfig.scheduleEndTime;
3257
+ element4.scheduleEndTime_iso = endTimeIso.format();
3258
+ element4.createdBy = new ObjectId( getCLconfig.createdBy );
3259
+ element4.createdByName = getCLconfig.createdByName;
3260
+ element4.sourceCheckList_id = getCLconfig._id;
3261
+ element4.checkListType = getCLconfig.checkListType;
3262
+ element4.storeCount = getCLconfig.storeCount;
3263
+ element4.questionCount = getCLconfig.questionCount;
3264
+ element4.publishDate = getCLconfig.publishDate;
3265
+ element4.locationCount = getCLconfig.locationCount;
3266
+ element4.scheduleRepeatedType = getCLconfig.scheduleRepeatedType;
3267
+ element4.approvalEnable = getCLconfig.approver.length ? true : false;
3268
+ element4.remainder = getCLconfig?.remainder || [];
3269
+ element4.restrictAttendance = getCLconfig?.restrictAttendance;
3270
+ element4.coverage = getCLconfig?.coverage;
3271
+ element4.rawImageUpload = getCLconfig?.rawImageUpload || false;
3272
+ assignUserList.push( { ...element4 } );
3273
+ }
3274
+ } ) );
3275
+
2228
3276
  if ( userIdList.length ) {
2229
- allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
3277
+ assignUserList = assignUserList.filter( ( item ) => typeof item._id == 'undefined' );
2230
3278
  }
2231
- if ( allQuestion ) {
3279
+ if ( assignUserList ) {
2232
3280
  if ( getCLconfig?.allowedMultiSubmit || processId ) {
2233
3281
  if ( processId ) {
2234
3282
  let processedDetails = await processedchecklist.findOne( { _id: processId } );
2235
3283
  if ( processedDetails ) {
2236
- let submitUser = allQuestion.find( ( item ) => item.userId.toString() == processedDetails.userId.toString() && item.store_id == processedDetails.store_id );
3284
+ 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
3285
  await processedchecklist.insertMany( submitUser );
2238
3286
  }
2239
3287
  } else {
2240
- let deleteQuery = {
3288
+ let deleteInprogressQuery = {
2241
3289
  date_string: insertdata.date_string,
2242
3290
  date_iso: insertdata.date_iso,
2243
3291
  client_id: insertdata.client_id,
2244
3292
  checkListId: updatedchecklist._id,
2245
- checklistStatus: { $nin: [ 'submit' ] },
3293
+ checklistStatus: { $nin: [ 'submit', 'inprogress' ] },
3294
+ redoStatus: false,
2246
3295
  };
2247
- await processedchecklist.deleteMany( deleteQuery );
2248
- await processedchecklist.insertMany( allQuestion );
3296
+ await processedchecklist.deleteMany( deleteInprogressQuery );
3297
+ deleteInprogressQuery.checklistStatus = 'inprogress';
3298
+ deleteInprogressQuery.redoStatus = false;
3299
+ let getInprogressData = await processedchecklist.find( deleteInprogressQuery, { userId: 1, store_id: 1 } );
3300
+ if ( getInprogressData ) {
3301
+ assignUserList = assignUserList.filter( ( item ) => {
3302
+ 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() );
3303
+ if ( !inprogressData ) {
3304
+ return item;
3305
+ }
3306
+ } );
3307
+ }
3308
+ if ( assignUserList.length ) {
3309
+ await processedchecklist.insertMany( assignUserList );
3310
+ }
2249
3311
  }
2250
3312
  } else {
2251
- let unAssignedList = allQuestion.reduce( ( acc, item ) => {
3313
+ let unAssignedList = assignUserList.reduce( ( acc, item ) => {
2252
3314
  if ( !acc[item.userEmail] ) {
2253
3315
  acc[item.userEmail]=[ item.store_id ];
2254
3316
  } else {
@@ -2260,17 +3322,36 @@ async function insertPCBulkV3( getCLconfig, checklistId, currentdate, updatedche
2260
3322
  let userList = Object.keys( unAssignedList );
2261
3323
 
2262
3324
  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' ] } } );
3325
+ if ( getCLconfig.coverage == 'store' ) {
3326
+ for ( let key in unAssignedList ) {
3327
+ if ( unAssignedList.hasOwnProperty( key ) ) {
3328
+ 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
+ }
2267
3330
  }
2268
3331
  }
2269
3332
 
3333
+ let inprogressData = await processedchecklist.find( {
3334
+ date_string: insertdata.date_string,
3335
+ date_iso: insertdata.date_iso,
3336
+ client_id: insertdata.client_id,
3337
+ checkListId: updatedchecklist._id,
3338
+ checklistStatus: 'inprogress',
3339
+ }, { userId: 1, store_id: 1 } );
3340
+
3341
+ if ( inprogressData.length ) {
3342
+ assignUserList = assignUserList.filter( ( item ) => {
3343
+ let findData = inprogressData.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
3344
+ if ( !findData ) {
3345
+ return item;
3346
+ }
3347
+ } );
3348
+ }
2270
3349
 
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
- } ) );
3350
+ await processedchecklist.deleteMany( { date_string: insertdata.date_string,
3351
+ date_iso: insertdata.date_iso,
3352
+ client_id: insertdata.client_id,
3353
+ checkListId: updatedchecklist._id, checklistStatus: 'open' } );
3354
+ await processedchecklist.insertMany( assignUserList );
2274
3355
  }
2275
3356
 
2276
3357
  tokenList.forEach( ( item ) => {
@@ -2345,7 +3426,7 @@ async function updateOpenSearch( user, data ) {
2345
3426
  export const aiChecklist = async ( req, res ) => {
2346
3427
  try {
2347
3428
  let storeDetails = await storeService.count( { clientId: req.query.clientId, status: 'active' } );
2348
- let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring' ];
3429
+ let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall' ];
2349
3430
  let checklistDetails = [];
2350
3431
  let publishList = [];
2351
3432
  let unpublishList = [];
@@ -2534,3 +3615,246 @@ export const preDefinedChecklist = async ( req, res ) => {
2534
3615
  }
2535
3616
  };
2536
3617
 
3618
+ export const selectAssign = async ( req, res ) => {
3619
+ try {
3620
+ let requestData = req.body;
3621
+ let resuldData;
3622
+ if ( requestData.coverage == 'store' ) {
3623
+ // //Select Store and cluster
3624
+ if ( requestData.assignType == 'store' ) {
3625
+ let storeQuery = [
3626
+ { $match: { clientId: requestData.clientId, status: 'active' } },
3627
+ {
3628
+ $project: {
3629
+ storeName: 1,
3630
+ storeId: 1,
3631
+ type: 'store',
3632
+ userName: { $arrayElemAt: [ '$spocDetails.name', 0 ] },
3633
+ userEmail: { $arrayElemAt: [ '$spocDetails.email', 0 ] },
3634
+ contact: { $arrayElemAt: [ '$spocDetails.contact', 0 ] },
3635
+ city: '$storeProfile.city',
3636
+ },
3637
+ },
3638
+
3639
+ ];
3640
+ resuldData = await storeService.aggregate( storeQuery );
3641
+ } else {
3642
+ let clusterQuery = [
3643
+ { $match: { clientId: requestData.clientId } },
3644
+ { $project: { 'clusterName': 1, 'type': 'cluster' } },
3645
+ ];
3646
+ resuldData = await clusterServices.aggregateCluster( clusterQuery );
3647
+ }
3648
+ // console.log( 'getStores =>', getStores );
3649
+ // console.log( 'getClusters =>', getClusters );
3650
+ } else if ( requestData.coverage == 'user' ) {
3651
+ // //Select User and Teams
3652
+ if ( requestData.assignType == 'user' ) {
3653
+ let userQuery = [
3654
+ { $match: { clientId: requestData.clientId, isActive: true } },
3655
+ { $project: { 'userEmail': '$email', 'userName': 1, 'type': 'user' } },
3656
+ ];
3657
+ resuldData = await userService.aggregate( userQuery );
3658
+ } else {
3659
+ let teamQuery = [
3660
+ { $match: { clientId: requestData.clientId } },
3661
+ { $project: { 'teamName': 1, 'type': 'teams' } },
3662
+ ];
3663
+ resuldData = await teamsServices.aggregateTeams( teamQuery );
3664
+ }
3665
+ // let getUsers = await userService.aggregate( userQuery );
3666
+ // console.log( 'getUsers =>', getUsers );
3667
+
3668
+ // let getTeams = await teamsServices.aggregateTeams( teamQuery );
3669
+ // console.log( 'getTeams =>', getTeams );
3670
+ }
3671
+ return res.sendSuccess( { 'totalCount': resuldData.length, 'data': resuldData } );
3672
+ } catch ( e ) {
3673
+ console.log( 'e =>', e );
3674
+ logger.error( 'selectAssign =>', e );
3675
+ return res.sendError( e, 500 );
3676
+ }
3677
+ };
3678
+
3679
+ async function assignUsers( data ) {
3680
+ let assignedData;
3681
+ if ( data?.type == 'cluster' ) {
3682
+ let clusterDetails = await clusterServices.findcluster( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3683
+ if ( clusterDetails.length ) {
3684
+ let clusterList = clusterDetails[0].stores.map( ( ele ) => ele.store );
3685
+ let storeDetails = await storeService.find( { _id: { $in: clusterList }, status: 'active' } );
3686
+ assignedData = await Promise.all( storeDetails.map( async ( store ) => {
3687
+ let userData = {
3688
+ storeId: store.storeId,
3689
+ storeName: store.storeName,
3690
+ userName: store.spocDetails?.[0]?.name,
3691
+ userEmail: store.spocDetails?.[0]?.email,
3692
+ clusterName: clusterDetails?.[0]?.clusterName,
3693
+ id: clusterDetails?.[0]?._id,
3694
+ };
3695
+ return userData;
3696
+ } ) );
3697
+ }
3698
+ } else {
3699
+ let teamDetails = await teamsServices.findteams( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3700
+ if ( teamDetails.length ) {
3701
+ let userIdList = [ ...teamDetails[0].users.map( ( ele ) => ele.userId ), ...teamDetails[0].Teamlead.map( ( ele ) => ele.userId ) ];
3702
+ let userDetails = await userService.find( { _id: userIdList } );
3703
+ assignedData = userDetails.map( ( user ) => {
3704
+ let userData = {
3705
+ userName: user.userName,
3706
+ userEmail: user.email,
3707
+ teamName: teamDetails?.[0]?.teamName,
3708
+ id: teamDetails?.[0]?._id,
3709
+ };
3710
+ return userData;
3711
+ } );
3712
+ }
3713
+ }
3714
+ return assignedData;
3715
+ }
3716
+
3717
+ export async function checklistAssign( req, res ) {
3718
+ try {
3719
+ if ( !req.body.checklistId ) {
3720
+ return res.sendError( 'Checklist id is required', 400 );
3721
+ }
3722
+ if ( !req.body.coverage ) {
3723
+ return res.sendError( 'Coverage is required', 400 );
3724
+ }
3725
+ if ( !req.body.idList ) {
3726
+ return res.sendError( 'Id is required', 400 );
3727
+ }
3728
+
3729
+ let checklistDetails = await checklistService.findOne( { _id: req.body.checklistId } );
3730
+ if ( !checklistDetails ) {
3731
+ return res.sendError( 'No data found', 204 );
3732
+ }
3733
+
3734
+ let uniqueArr = [];
3735
+
3736
+ await Promise.all( req.body.idList.map( async ( data ) => {
3737
+ let assignedData = {
3738
+ ...data,
3739
+ clientId: req.body.clientId,
3740
+ };
3741
+ let uploadData = await assignUsers( assignedData );
3742
+ if ( uploadData?.length ) {
3743
+ uniqueArr.push( ...uploadData );
3744
+ }
3745
+ } ) );
3746
+
3747
+ if ( uniqueArr.length ) {
3748
+ if ( req.body.coverage == 'store' ) {
3749
+ uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3750
+ if ( acc[obj.storeName] ) {
3751
+ acc[obj.storeName].clusterName += ',' + obj.clusterName;
3752
+ } else {
3753
+ acc[obj.storeName] = { ...obj };
3754
+ }
3755
+ return acc;
3756
+ }, {} );
3757
+
3758
+ uniqueArr= Object.values( uniqueArr );
3759
+ } else {
3760
+ uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3761
+ if ( acc[obj.userEmail] ) {
3762
+ acc[obj.userEmail].teamName += ','+ obj.teamName;
3763
+ } else {
3764
+ acc[obj.userEmail] = { ...obj };
3765
+ }
3766
+ return acc;
3767
+ }, {} );
3768
+ uniqueArr = Object.values( uniqueArr );
3769
+ }
3770
+ }
3771
+
3772
+ return res.sendSuccess( { count: uniqueArr.length, uniqueArr } );
3773
+ } catch ( e ) {
3774
+ logger.error( { functionName: 'checklistAssign', error: e } );
3775
+ return res.sendError( e, 500 );
3776
+ }
3777
+ }
3778
+
3779
+ export async function updateAssign( req, res ) {
3780
+ try {
3781
+ // if ( !req.body.assignedList.length && !req.body.assignedGroup.length ) {
3782
+ // return res.sendError( 'No data found', 204 );
3783
+ // }
3784
+ let checklistDetails = await checklistService.findOne( { _id: req.body.checkListId, client_id: req.body.clientId } );
3785
+ if ( !checklistDetails ) {
3786
+ return res.sendError( 'No data found', 204 );
3787
+ }
3788
+ req.body.assignedGroup = [ ...new Set( req.body.assignedGroup.map( ( item ) => item.id ) ) ];
3789
+ // req.body.assignedGroup = req.body.assignedGroup.map( ( ele ) => {
3790
+ // return { id: ele };
3791
+ // } );
3792
+ await assignedService.deleteMany( { checkListId: req.body.checkListId } );
3793
+ let assignedUserList = [];
3794
+ let userEmailList = req.body.assignedList.map( ( ele ) => ele.userEmail.toLowerCase() );
3795
+ let query = [
3796
+ {
3797
+ $addFields: {
3798
+ emailToLower: { $toLower: '$email' },
3799
+ },
3800
+ },
3801
+ {
3802
+ $match: {
3803
+ clientId: req.body.clientId,
3804
+ emailToLower: { $in: userEmailList },
3805
+ },
3806
+ },
3807
+ ];
3808
+ let assignUserDetails = await userService.aggregate( query );
3809
+ await Promise.all( req.body.assignedList.map( async ( assign ) => {
3810
+ let userDetails = assignUserDetails.find( ( ele ) => ele.email.toLowerCase() == assign.userEmail.toLowerCase() );
3811
+ if ( !userDetails ) {
3812
+ let userData = {
3813
+ userName: assign.userName,
3814
+ email: assign.userEmail,
3815
+ mobileNumber: assign?.userPhone || '',
3816
+ clientId: req.body.clientId,
3817
+ };
3818
+ userDetails = await createUser( userData );
3819
+ userDetails = userDetails;
3820
+ }
3821
+ let data = {
3822
+ ...assign,
3823
+ store_id: assign?.storeId,
3824
+ client_id: req.body.clientId,
3825
+ checkListId: req.body.checkListId,
3826
+ coverage: req.body.coverage,
3827
+ assignId: assign._id,
3828
+ userId: userDetails?._id,
3829
+ checkListName: checklistDetails.checkListName,
3830
+ };
3831
+ delete data._id;
3832
+ assignedUserList.push( data );
3833
+ } ) );
3834
+ let assignGroupDetails = [];
3835
+ if ( req.body.coverage == 'store' ) {
3836
+ assignGroupDetails = await clusterServices.findcluster( { _id: { $in: req.body.assignedGroup } } );
3837
+ } else {
3838
+ assignGroupDetails = await teamsServices.findteams( { _id: { $in: req.body.assignedGroup } } );
3839
+ }
3840
+ await Promise.all( req.body.assignedGroup.map( async ( assign ) => {
3841
+ let groupDetails = assignGroupDetails.find( ( ele ) => ele._id.toString() == assign );
3842
+ if ( groupDetails ) {
3843
+ let groupData = {
3844
+ client_id: req.body.clientId,
3845
+ checkListId: req.body.checkListId,
3846
+ coverage: req.body.coverage,
3847
+ assignId: assign,
3848
+ checkListName: checklistDetails.checkListName,
3849
+ ...( req.body.coverage == 'store' ) ? { clusterName: groupDetails?.clusterName } : { teamName: groupDetails?.teamName },
3850
+ };
3851
+ assignedUserList.push( groupData );
3852
+ }
3853
+ } ) );
3854
+ await assignedService.insertMany( assignedUserList );
3855
+ return res.sendSuccess( 'Assign details updated successfully' );
3856
+ } catch ( e ) {
3857
+ logger.error( { functionName: 'updateAssign', error: e } );
3858
+ return res.sendError( e, 500 );
3859
+ }
3860
+ }