tango-app-api-trax 3.4.0-flag-11 → 3.4.1-activitylog-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.
@@ -1,4 +1,4 @@
1
- import { signedUrl, fileUpload, chunkArray, logger, sendPushNotification, insertOpenSearchData } from 'tango-app-api-middleware';
1
+ import { signedUrl, fileUpload, chunkArray, logger, sendPushNotification, sendTeamsNotification, insertOpenSearchData } from 'tango-app-api-middleware';
2
2
  import * as checklistService from '../services/checklist.service.js';
3
3
  import * as questionService from '../services/checklistQuestion.service.js';
4
4
  import * as assignedService from '../services/checklistAssign.service.js';
@@ -24,6 +24,7 @@ dayjs.extend( customParseFormat );
24
24
  import * as clusterServices from '../services/cluster.service.js';
25
25
  import * as teamsServices from '../services/teams.service.js';
26
26
 
27
+
27
28
  export const checklist = async ( req, res ) => {
28
29
  try {
29
30
  let limit = parseInt( req.query.limit ) || 10;
@@ -128,6 +129,7 @@ export const checklist = async ( req, res ) => {
128
129
 
129
130
  export const create = async ( req, res ) => {
130
131
  try {
132
+ console.log( 'create' );
131
133
  let inputBody = req.body;
132
134
  let checkNumber;
133
135
  let questionCount = 0;
@@ -275,13 +277,20 @@ export const create = async ( req, res ) => {
275
277
  section: section.name,
276
278
  createdBy: req.user._id,
277
279
  createdByName: req.user.userName,
278
- client_id: inputBody.clientId,
280
+ client_id: req.body.clientId,
279
281
  checkListId: checkListId,
280
282
  question: section.questions,
281
283
  checkList: inputBody.checklistName,
282
284
  };
283
285
  await questionService.create( sectionList ).then( async ( data ) => {
284
286
  if ( i == inputBody.sections.length - 1 ) {
287
+ let actionType = 'created';
288
+ let teamsMsg;
289
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
290
+ actionType = 'Create';
291
+ teamsMsg = 'ClientId: '+ req.body.clientId + ', Action: '+ actionType + ', ChecklistId: '+ checkListId + ', Checklist Name: '+ inputBody.checklistName + ', UpDatedBy: '+ req.user.email;
292
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
293
+
285
294
  let logObj = {
286
295
  client_id: inputBody.clientId,
287
296
  createAt: new Date(),
@@ -296,8 +305,33 @@ export const create = async ( req, res ) => {
296
305
  createdBy: req.user.userName,
297
306
  coverage: 'store',
298
307
  logDetails: {},
308
+ userType: req.user.userType,
299
309
  };
300
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
310
+ console.log( 'req.user', req.user );
311
+ console.log( 'logObj', logObj );
312
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
313
+ if ( inputBody.submitType == 'save' ) {
314
+ console.log( 'logObj', logObj );
315
+ let logObj = {
316
+ client_id: inputBody.clientId,
317
+ createAt: new Date(),
318
+ sourceCheckList_id: checkListId,
319
+ checkListName: inputBody.checklistName,
320
+ fromCheckListName: '',
321
+ type: 'checklist',
322
+ action: 'draft',
323
+ storeName: '',
324
+ store_id: '',
325
+ createdByEmail: req.user.email,
326
+ createdBy: req.user.userName,
327
+ coverage: 'store',
328
+ logDetails: {},
329
+ userType: req.user.userType,
330
+ };
331
+
332
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
333
+ }
334
+
301
335
  return res.sendSuccess( { checklistId: checkListId, msg: 'CheckList Created Successfully' } );
302
336
  }
303
337
  } ).catch( ( e ) => {
@@ -314,6 +348,7 @@ export const create = async ( req, res ) => {
314
348
  return res.sendError( e, 500 );
315
349
  } );
316
350
  } catch ( e ) {
351
+ console.log( 'e', e );
317
352
  logger.error( 'create =>', e );
318
353
  return res.sendError( e, 500 );
319
354
  }
@@ -621,6 +656,30 @@ export const deleteChecklist = async ( req, res ) => {
621
656
  await processedchecklist.deleteMany( { date_string: { $ne: date }, date_iso: { $gt: date }, sourceCheckList_id: req.params.checklistId, checklistStatus: { $ne: 'submit' } } );
622
657
  logger.info( { function: 'deleteChecklist', query: { date_string: { $ne: date }, date_iso: { $gt: date }, sourceCheckList_id: req.params.checklistId, checklistStatus: { $ne: 'submit' } } } );
623
658
  checklistDetails.save().then( () => {
659
+ let actionType = 'Deleted';
660
+ let teamsMsg;
661
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
662
+ teamsMsg = 'ClientId: '+ checklistDetails.client_id + ', Action: '+ actionType + ', ChecklistId: '+ req.params.checklistId + ', Checklist Name: '+ checklistDetails.checkListName + ', UpDatedBy: '+ req.user.email;
663
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
664
+
665
+ let logObj = {
666
+ client_id: checklistDetails.client_id,
667
+ createAt: new Date(),
668
+ sourceCheckList_id: checklistDetails._id,
669
+ checkListName: checklistDetails.checkListName,
670
+ fromCheckListName: '',
671
+ type: 'checklist',
672
+ action: 'deleted',
673
+ storeName: '',
674
+ store_id: '',
675
+ createdByEmail: req.user.email,
676
+ createdBy: req.user.userName,
677
+ coverage: checklistDetails.coverage,
678
+ logDetails: {},
679
+ userType: req.user.userType,
680
+ };
681
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
682
+
624
683
  return res.sendSuccess( { message: 'Checklist Deleted Successfully' } );
625
684
  } ).catch( ( e ) => {
626
685
  return res.sendError( e, 500 );
@@ -694,6 +753,29 @@ export const duplicateChecklist = async ( req, res ) => {
694
753
  sections.push( sectionDetails );
695
754
  }
696
755
  await questionService.insertMany( sections );
756
+ let actionType = 'Duplicated';
757
+ let teamsMsg;
758
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
759
+ teamsMsg = 'ClientId: '+ checkDetails.client_id + ', Action: '+ actionType + ', ChecklistId: '+ data._id + ', Checklist Name: '+ checkDetails.checkListName + ', UpDatedBy: '+ req.user.email;
760
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
761
+
762
+ let logObj = {
763
+ client_id: checkDetails.client_id,
764
+ createAt: new Date(),
765
+ sourceCheckList_id: checkDetails._id,
766
+ checkListName: checkDetails.checkListName,
767
+ fromCheckListName: '',
768
+ type: 'checklist',
769
+ action: 'duplicated',
770
+ storeName: '',
771
+ store_id: '',
772
+ createdByEmail: req.user.email,
773
+ createdBy: req.user.userName,
774
+ coverage: checkDetails.coverage,
775
+ logDetails: {},
776
+ userType: req.user.userType,
777
+ };
778
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
697
779
  return res.sendSuccess( { message: 'CheckList Duplicated Successfully' } );
698
780
  } else {
699
781
  return res.sendSuccess( { message: 'duplicated Successfully' } );
@@ -742,13 +824,14 @@ export const update = async ( req, res ) => {
742
824
  }
743
825
  } );
744
826
 
827
+
745
828
  let params = {
746
829
  checkListName: inputBody.checklistName,
747
830
  checkListDescription: inputBody.checklistDescription,
748
831
  questionCount: questionCount,
749
832
  };
750
833
 
751
- checkListDetails.updateOne( { _id: req.params.checklistId }, params );
834
+ await checklistService.updateOne( { _id: req.params.checklistId }, params );
752
835
  let checkListId = req.params.checklistId;
753
836
  let logInsertData = {
754
837
  action: 'checklistUpdate',
@@ -874,7 +957,7 @@ export const update = async ( req, res ) => {
874
957
  delete ans.answeroptionNumber;
875
958
  } );
876
959
  let compare = findDifferences( qn, question );
877
- if ( Object.keys( compare ).length && ( compare?.answerType || compare?.answers || compare?.linkType || compare?.qname ) ) {
960
+ if ( Object.keys( compare ).length ) {
878
961
  questionList.questionEdit.push( { sectionName: ele.section, questions: [ { previous: qn, new: question } ] } );
879
962
  }
880
963
  } else {
@@ -939,14 +1022,40 @@ export const update = async ( req, res ) => {
939
1022
  questionAdd: questionList.questionAdd,
940
1023
  questionEdit: questionList.questionEdit,
941
1024
  questionDelete: questionList.questionDelete,
1025
+ userType: req.user.userType,
942
1026
  },
943
1027
  };
944
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertLogData );
1028
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertLogData );
945
1029
  }
1030
+
1031
+ if ( inputBody.submitType == 'save' ) {
1032
+ let logObj = {
1033
+ client_id: inputBody.clientId,
1034
+ createAt: new Date(),
1035
+ sourceCheckList_id: req.params.checklistId,
1036
+ checkListName: inputBody.checklistName,
1037
+ fromCheckListName: '',
1038
+ type: 'checklist',
1039
+ action: 'draft',
1040
+ storeName: '',
1041
+ store_id: '',
1042
+ createdByEmail: req.user.email,
1043
+ createdBy: req.user.userName,
1044
+ coverage: 'store',
1045
+ logDetails: {},
1046
+ userType: req.user.userType,
1047
+ };
1048
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1049
+ }
1050
+ let actionType = 'Checklist Updated';
1051
+ let teamsMsg;
1052
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
1053
+ teamsMsg = 'ClientId: '+ req.body.clientId + ', Action: '+ actionType + ', ChecklistId: '+ checkListId + ', Checklist Name: '+ inputBody.checklistName + ', UpDatedBy: '+ req.user.email;
1054
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
946
1055
  return res.sendSuccess( { message: 'CheckList Updated Successfully', checklistId: req.params.checklistId } );
947
1056
  } catch ( e ) {
948
- logger.error( { functionName: 'questionUpdate', error: e } );
949
- res.sendError( e, 500 );
1057
+ logger.error( 'update =>', e );
1058
+ return res.sendError( e, 500 );
950
1059
  }
951
1060
  };
952
1061
 
@@ -1569,6 +1678,7 @@ export const updateConfigurev1 =async ( req, res ) => {
1569
1678
  await checklistLogs.create( logInsertData );
1570
1679
 
1571
1680
  checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist', isdeleted: false } );
1681
+ let oldPublish = checklistDetails.publish;
1572
1682
 
1573
1683
  if ( [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection' ].includes( inputBody.checkListDetails.checkListType ) && inputBody.uploadUser ) {
1574
1684
  checklistDetails = await checklistService.findOne( { _id: inputBody.checkListDetails._id, type: 'checklist' } );
@@ -1581,8 +1691,9 @@ export const updateConfigurev1 =async ( req, res ) => {
1581
1691
  if ( inputBody.timeZone ) {
1582
1692
  currentDate = dayjs().tz( inputBody.timeZone ).format();
1583
1693
  } else {
1584
- currentDate = dayjs().format();
1694
+ currentDate = dayjs().format( 'HH:mm:ss' );
1585
1695
  }
1696
+ currentDate = dayjs.utc( currentDate, 'HH:mm:ss' ).format();
1586
1697
  let updatedscheduleEndTimeISO = dayjs.utc( inputBody?.checkListDetails?.scheduleEndTime, 'hh:mm A' ).format( 'HH:mm:ss' );
1587
1698
  let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1588
1699
 
@@ -1730,15 +1841,21 @@ export const updateConfigurev1 =async ( req, res ) => {
1730
1841
  checklistDetails.configEndDate = checklistDetails.configEndDate ? dayjs.utc( checklistDetails?.configEndDate ).format( 'YYYY-MM-DD' ) : '';
1731
1842
  checklistDetails.scheduleDate = checklistDetails.scheduleDate ? dayjs.utc( checklistDetails?.scheduleDate ).format( 'YYYY-MM-DD' ) : '';
1732
1843
  checklistDetails.scheduleRepeatedDay = Array.isArray( checklistDetails.scheduleRepeatedDay ) ? checklistDetails.scheduleRepeatedDay[0] : checklistDetails.scheduleRepeatedDay;
1733
- configDetails.scheduleRepeatedDay = Array.isArray( configDetails.scheduleRepeatedDay ) ? configDetails?.scheduleRepeatedDay[0] : configDetails?.scheduleRepeatedDay;
1844
+ configDetails.scheduleRepeatedDay = Array.isArray( configDetails.scheduleRepeatedDay ) ? configDetails?.scheduleRepeatedDay?.[0] || '' : configDetails?.scheduleRepeatedDay;
1734
1845
  configDetails.scheduleDate = configDetails.scheduleDate ? dayjs( configDetails?.scheduleDate ).format( 'YYYY-MM-DD' ) : '';
1735
- let removedKeys = [ 'publish', 'publishDate', 'storeCount', 'sections', 'createdAt', 'updatedAt', 'scheduleStartTimeISO', 'scheduleEndTimeISO' ];
1846
+ let removedKeys = [ 'publish', 'publishDate', 'storeCount', 'sections', 'createdAt', 'updatedAt', 'scheduleStartTimeISO', 'scheduleEndTimeISO', 'aiConfig' ];
1736
1847
  removedKeys.forEach( ( item ) => {
1737
1848
  delete configDetails?.[item];
1738
1849
  delete checklistDetails?.[item];
1739
1850
  } );
1740
1851
  let differences = findObjectDifference( checklistDetails, configDetails );
1741
- if ( Object.keys( differences ).length || req.body.added.length || req.body.removed.length ) {
1852
+ if ( Object.keys( differences ).length || req.body.added.length || req.body.removed?.user?.length || req.body.removed?.store?.length ) {
1853
+ let showSchedule = false;
1854
+ let scheduleKeys = [ 'scheduleDate', 'schedule', 'scheduleEndTime', 'scheduleStartTime', 'scheduleRepeatedDay', 'scheduleRepeatedType', 'configStartDate', 'configEndDate', 'scheduleWeekDays', 'scheduleRepeatedMonthWeek', 'specificDate' ];
1855
+
1856
+ if ( scheduleKeys.some( ( key ) => differences?.[key] ) ) {
1857
+ showSchedule = true;
1858
+ }
1742
1859
  let insertData = {
1743
1860
  client_id: req.body.clientId,
1744
1861
  createAt: new Date(),
@@ -1746,7 +1863,7 @@ export const updateConfigurev1 =async ( req, res ) => {
1746
1863
  checkListName: configDetails.checkListName,
1747
1864
  fromCheckListName: '',
1748
1865
  type: 'checklist',
1749
- action: 'updated',
1866
+ action: inputBody.checkListDetails.publish ? 'updated' : 'draft',
1750
1867
  storeName: '',
1751
1868
  store_id: '',
1752
1869
  createdByEmail: req.user.email,
@@ -1755,29 +1872,29 @@ export const updateConfigurev1 =async ( req, res ) => {
1755
1872
  logDetails: {
1756
1873
  schedule: {
1757
1874
  previous: {
1758
- ...( differences?.scheduleDate && ( differences?.scheduleDate.previous != '' && differences?.scheduleDate.previous != null ) ) ? { scheduleDate: dayjs( checklistDetails?.scheduleDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1759
- schedule: differences?.schedule ? checklistDetails.schedule : '',
1760
- time: ( ( differences?.scheduleEndTime || differences?.scheduleStartTime ) && ( checklistDetails.scheduleStartTime != '' || checklistDetails.scheduleEndTime != '' ) ) ? checklistDetails.scheduleStartTime + ' to ' + checklistDetails.scheduleEndTime : '',
1761
- scheduleRepeatedDay: differences?.scheduleRepeatedDay ? checklistDetails?.scheduleRepeatedDay : '',
1762
- scheduleRepeatedType: differences?.scheduleRepeatedType ? checklistDetails?.scheduleRepeatedType : '',
1763
- ...( differences?.configStartDate && checklistDetails?.configStartDate ) ? { configStartDate: dayjs( checklistDetails?.configStartDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1764
- ...( differences?.configEndDate && checklistDetails?.configEndDate ) ? { configEndDate: dayjs( checklistDetails?.configEndDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1765
- scheduleWeekDays: differences?.scheduleWeekDays ? checklistDetails?.scheduleWeekDays : [],
1766
- scheduleRepeatedMonthWeek: differences?.scheduleRepeatedMonthWeek ? checklistDetails?.scheduleRepeatedMonthWeek : '',
1767
- specificDate: differences?.specificDate ? checklistDetails?.specificDate : [],
1875
+ ...( showSchedule && checklistDetails.schedule == 'onetime' ) ? { scheduleDate: dayjs( checklistDetails?.scheduleDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1876
+ schedule: showSchedule ? checklistDetails.schedule : '',
1877
+ time: ( ( showSchedule ) && ( checklistDetails.scheduleStartTime != '' || checklistDetails.scheduleEndTime != '' ) ) ? checklistDetails.scheduleStartTime + ' to ' + checklistDetails.scheduleEndTime : '',
1878
+ scheduleRepeatedDay: showSchedule ? checklistDetails?.scheduleRepeatedDay : '',
1879
+ scheduleRepeatedType: showSchedule ? checklistDetails?.scheduleRepeatedType : '',
1880
+ ...( showSchedule && checklistDetails?.configStartDate ) ? { configStartDate: dayjs( checklistDetails?.configStartDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1881
+ ...( showSchedule && checklistDetails?.configEndDate ) ? { configEndDate: dayjs( checklistDetails?.configEndDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1882
+ scheduleWeekDays: showSchedule ? checklistDetails?.scheduleWeekDays : [],
1883
+ scheduleRepeatedMonthWeek: showSchedule ? checklistDetails?.scheduleRepeatedMonthWeek : '',
1884
+ specificDate: showSchedule ? checklistDetails?.specificDate : [],
1768
1885
 
1769
1886
  },
1770
1887
  new: {
1771
- ...( differences?.scheduleDate && ( differences?.scheduleDate.new != '' && differences?.scheduleDate.new != null ) ) ? { scheduleDate: dayjs( configDetails?.scheduleDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1772
- schedule: differences?.schedule ? configDetails.schedule : '',
1773
- time: ( ( differences?.scheduleEndTime || differences?.scheduleStartTime ) && ( configDetails.scheduleStartTime != '' || configDetails.scheduleEndTime != '' ) ) ? configDetails.scheduleStartTime + ' to ' + configDetails.scheduleEndTime : '',
1774
- scheduleRepeatedDay: differences?.scheduleRepeatedDay ? configDetails?.scheduleRepeatedDay : '',
1775
- scheduleRepeatedType: differences?.scheduleRepeatedType ? configDetails?.scheduleRepeatedType : '',
1776
- ...( differences?.configStartDate && configDetails?.configStartDate ) ? { configStartDate: dayjs( configDetails?.configStartDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1777
- ...( differences?.configEndDate && configDetails?.configEndDate ) ? { configEndDate: dayjs( configDetails?.configEndDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1778
- scheduleWeekDays: differences?.scheduleWeekDays ? configDetails?.scheduleWeekDays : [],
1779
- scheduleRepeatedMonthWeek: differences?.scheduleRepeatedMonthWeek ? configDetails?.scheduleRepeatedMonthWeek : '',
1780
- specificDate: differences?.specificDate ? configDetails?.specificDate : [],
1888
+ ...( showSchedule && configDetails.schedule == 'onetime' ) ? { scheduleDate: dayjs( configDetails?.scheduleDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1889
+ schedule: showSchedule ? configDetails.schedule : '',
1890
+ time: ( ( showSchedule ) && ( configDetails.scheduleStartTime != '' || configDetails.scheduleEndTime != '' ) ) ? configDetails.scheduleStartTime + ' to ' + configDetails.scheduleEndTime : '',
1891
+ scheduleRepeatedDay: showSchedule ? configDetails?.scheduleRepeatedDay : '',
1892
+ scheduleRepeatedType: showSchedule ? configDetails?.scheduleRepeatedType : '',
1893
+ ...( showSchedule && configDetails?.configStartDate ) ? { configStartDate: dayjs( configDetails?.configStartDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1894
+ ...( showSchedule && configDetails?.configEndDate ) ? { configEndDate: dayjs( configDetails?.configEndDate, 'YYYY-MM-DD' ).format( 'DD MMM, YYYY' ) } :{},
1895
+ scheduleWeekDays: showSchedule ? configDetails?.scheduleWeekDays : [],
1896
+ scheduleRepeatedMonthWeek: showSchedule ? configDetails?.scheduleRepeatedMonthWeek : '',
1897
+ specificDate: showSchedule ? configDetails?.specificDate : [],
1781
1898
  },
1782
1899
  },
1783
1900
  response: {
@@ -1795,39 +1912,48 @@ export const updateConfigurev1 =async ( req, res ) => {
1795
1912
  ],
1796
1913
  },
1797
1914
  ...( differences?.approver ) ? { approver:
1798
- { previous: differences?.approver?.previous.map( ( item ) => item.name ).toString(),
1799
- new: differences?.approver?.new.map( ( item ) => item.name ).toString() },
1915
+ { previous: checklistDetails?.approver.map( ( item ) => item.name ).toString(),
1916
+ new: configDetails?.approver.map( ( item ) => item.name ).toString() },
1800
1917
  } : { approver: {} },
1801
1918
  ...( differences?.owner ) ? { owner:
1802
- { previous: differences?.owner?.previous.map( ( item ) => item.name ).toString(),
1803
- new: differences?.owner?.new.map( ( item ) => item.name ).toString() },
1919
+ { previous: checklistDetails?.owner.map( ( item ) => item.name ).toString(),
1920
+ new: configDetails?.owner.map( ( item ) => item.name ).toString() },
1804
1921
  } : { owner: {} },
1805
1922
  ...( req.body.checkListDetails.coverage == 'store' ) ? { storeAdded: req.body.added } :{ storeAdded: [] },
1806
- ...( req.body.checkListDetails.coverage == 'store' ) ? { storeRemoved: req.body.removed } :{ storeRemoved: [] },
1923
+ ...( req.body.removed.store.length ) ? { storeRemoved: req.body.removed.store } :{ storeRemoved: [] },
1807
1924
  ...( req.body.checkListDetails.coverage == 'user' ) ? { userAdded: req.body.added } :{ userAdded: [] },
1808
- ...( req.body.checkListDetails.coverage == 'user' ) ? { userRemoved: req.body.removed } :{ userRemoved: [] },
1925
+ ...( req.body.removed.user.length ) ? { userRemoved: req.body.removed.user } :{ userRemoved: [] },
1809
1926
  },
1927
+ userType: req.user.userType,
1810
1928
  };
1811
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertData );
1929
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertData );
1812
1930
  }
1813
1931
 
1814
- let logObj = {
1815
- client_id: inputBody.checkListDetails.client_id,
1816
- createAt: new Date(),
1817
- sourceCheckList_id: inputBody.checkListDetails._id,
1818
- checkListName: inputBody.checkListDetails.checkListName,
1819
- fromCheckListName: '',
1820
- type: 'checklist',
1821
- action: inputBody.checkListDetails.publish ? 'published' : 'unpublished',
1822
- storeName: '',
1823
- store_id: '',
1824
- createdByEmail: req.user.email,
1825
- createdBy: req.user.userName,
1826
- coverage: inputBody.checkListDetails.coverage,
1827
- logDetails: {},
1828
- };
1829
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1830
-
1932
+ if ( inputBody.checkListDetails.publish != oldPublish ) {
1933
+ let logObj = {
1934
+ client_id: inputBody.checkListDetails.client_id,
1935
+ createAt: new Date(),
1936
+ sourceCheckList_id: inputBody.checkListDetails._id,
1937
+ checkListName: inputBody.checkListDetails.checkListName,
1938
+ fromCheckListName: '',
1939
+ type: 'checklist',
1940
+ action: inputBody.checkListDetails.publish ? 'published' : 'unpublished',
1941
+ storeName: '',
1942
+ store_id: '',
1943
+ createdByEmail: req.user.email,
1944
+ createdBy: req.user.userName,
1945
+ coverage: inputBody.checkListDetails.coverage,
1946
+ logDetails: {},
1947
+ userType: req.user.userType,
1948
+ };
1949
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1950
+ }
1951
+ let actionType;
1952
+ let teamsMsg;
1953
+ actionType = inputBody.checkListDetails.publish ? 'configPublish' : 'configDraft';
1954
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
1955
+ teamsMsg = 'ClientId: '+ checklistDetails.client_id + ', Action: '+ actionType + ', ChecklistId: '+ checklistDetails._id + ', Checklist Name: '+ checklistDetails.checkListName + ', UpDatedBy: '+ req.user.email;
1956
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
1831
1957
  if ( response?.modifiedCount || response?.matchedCount || response?.upsertedCount ) {
1832
1958
  return res.sendSuccess( { id, message: 'Configured Updated Successfully' } );
1833
1959
  }
@@ -1839,7 +1965,6 @@ export const updateConfigurev1 =async ( req, res ) => {
1839
1965
  return res.sendError( e, 500 );
1840
1966
  }
1841
1967
  };
1842
-
1843
1968
  function findObjectDifference( oldObj, newObj ) {
1844
1969
  const isEqual = ( a, b ) => JSON.stringify( a ) === JSON.stringify( b );
1845
1970
 
@@ -1954,13 +2079,15 @@ export const updatePublish = async ( req, res ) => {
1954
2079
  createdBy: req.user.userName,
1955
2080
  coverage: getCheckDetails.coverage,
1956
2081
  logDetails: {},
2082
+ userType: req.user.userType,
1957
2083
  };
1958
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
2084
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1959
2085
  if ( getCheckDetails.checkListType == 'custom' ) {
1960
2086
  let currentDate = dayjs.utc().format();
1961
2087
  let updatedscheduleEndTimeISO = dayjs.utc( getCheckDetails.scheduleEndTimeISO ).format( 'HH:mm:ss' );
1962
2088
  let newUpdatedDate = dayjs.utc( updatedscheduleEndTimeISO, 'HH:mm:ss' ).format();
1963
2089
 
2090
+
1964
2091
  if ( req.body.publish && req.body.publish == true ) {
1965
2092
  if ( newUpdatedDate > currentDate ) {
1966
2093
  let deleteQuery = {
@@ -2026,6 +2153,12 @@ export const updatePublish = async ( req, res ) => {
2026
2153
  createdByEmail: req.user.email,
2027
2154
  };
2028
2155
  await checklistLogs.create( logInsertData );
2156
+ let actionType;
2157
+ let teamsMsg;
2158
+ actionType = req.body.publish ? 'publish' : 'unpublish';
2159
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
2160
+ teamsMsg = 'ClientId: '+ getCheckDetails.client_id + ', Action: '+ actionType + ', ChecklistId: '+ getCheckDetails._id + ', Checklist Name: '+ getCheckDetails.checkListName + ', UpDatedBy: '+ req.user.email;
2161
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
2029
2162
  return res.sendSuccess( { checklistName: getCheckDetails.checkListName, message: 'Updated Successfully' } );
2030
2163
  } catch ( e ) {
2031
2164
  logger.error( 'updatePublish erroe =>', e );
@@ -2297,7 +2430,7 @@ export const validateUserv1 = async ( req, res ) => {
2297
2430
  {
2298
2431
  $project: {
2299
2432
  newEmail: { $toLower: '$email' },
2300
- isActive: 1,
2433
+ // isActive: 1,
2301
2434
  clientId: 1,
2302
2435
  email: 1,
2303
2436
  },
@@ -2305,7 +2438,7 @@ export const validateUserv1 = async ( req, res ) => {
2305
2438
  {
2306
2439
  $match: {
2307
2440
  newEmail: { $in: userEmailList },
2308
- isActive: true,
2441
+ // isActive: true,
2309
2442
  clientId: { $ne: req.body.clientId },
2310
2443
  },
2311
2444
  },
@@ -2347,7 +2480,7 @@ export const validateUserv1 = async ( req, res ) => {
2347
2480
  let newStoreList = storeList.filter( ( ele ) => ele != null && !existsStore.includes( ele.toLowerCase() ) );
2348
2481
  if ( req.body.coverage == 'store' ) {
2349
2482
  assignDetails.forEach( ( item ) => {
2350
- let getStoreDetails = storeDetails.find( ( store ) => store.storeName.toLowerCase() == item.storeName.toLowerCase() );
2483
+ let getStoreDetails = storeDetails.find( ( store ) => store.storeName.trim().toLowerCase() == item.storeName.trim().toLowerCase() );
2351
2484
  if ( getStoreDetails ) {
2352
2485
  let storeUserDetails = userDetails.find( ( ele ) => ele.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
2353
2486
  item._id = getStoreDetails._id;
@@ -2368,6 +2501,10 @@ export const validateUserv1 = async ( req, res ) => {
2368
2501
  } );
2369
2502
  }
2370
2503
 
2504
+ newStoreList = [ ...new Set( newStoreList.map( ( item ) => item ) ) ];
2505
+ newUserList = [ ...new Set( newUserList.map( ( item ) => item ) ) ];
2506
+ existEmail = [ ...new Set( existEmail.map( ( item ) => item ) ) ];
2507
+ inActiveStores = [ ...new Set( inActiveStores.map( ( item ) => item ) ) ];
2371
2508
  if ( ( newUserList.length || newStoreList.length || existEmail.length || inActiveStores.length ) && !req.body?.addUser ) {
2372
2509
  return res.sendError( { validate: false, user: newUserList, store: newStoreList, existEmail, inActiveStores, data: assignDetails }, 400 );
2373
2510
  }
@@ -2813,6 +2950,7 @@ export async function insertSingleProcessData( checklistId, processId = 0, oldDa
2813
2950
  insertdata.restrictAttendance = getCLconfig?.restrictAttendance;
2814
2951
  insertdata.coverage = getCLconfig?.coverage;
2815
2952
  insertdata.rawImageUpload = getCLconfig?.rawImageUpload || false;
2953
+ insertdata.rawVideoUpload = getCLconfig?.rawVideoUpload || false;
2816
2954
 
2817
2955
  let collectSections = [];
2818
2956
  let sectionQuery = [];
@@ -3525,6 +3663,7 @@ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedche
3525
3663
  element4.restrictAttendance = getCLconfig?.restrictAttendance;
3526
3664
  element4.coverage = getCLconfig?.coverage;
3527
3665
  element4.rawImageUpload = getCLconfig?.rawImageUpload || false;
3666
+ element4.rawVideoUpload = getCLconfig?.rawVideoUpload || false;
3528
3667
  assignUserList.push( { ...element4 } );
3529
3668
  }
3530
3669
  } ) );
@@ -3566,25 +3705,19 @@ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedche
3566
3705
  }
3567
3706
  }
3568
3707
  } else {
3569
- let unAssignedList = assignUserList.reduce( ( acc, item ) => {
3570
- if ( !acc[item.userEmail] ) {
3571
- acc[item.userEmail]=[ item.store_id ];
3572
- } else {
3573
- acc[item.userEmail].push( item.store_id );
3574
- }
3575
- return acc;
3576
- }, {} );
3708
+ let deletedList = [];
3709
+
3710
+ await processedchecklist.deleteMany( { date_string: insertdata.date_string,
3711
+ date_iso: insertdata.date_iso,
3712
+ client_id: insertdata.client_id,
3713
+ checkListId: updatedchecklist._id, checklistStatus: 'open' } );
3577
3714
 
3578
- let userList = Object.keys( unAssignedList );
3579
3715
 
3580
- 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' ] } } );
3581
- if ( getCLconfig.coverage == 'store' ) {
3582
- for ( let key in unAssignedList ) {
3583
- if ( unAssignedList.hasOwnProperty( key ) ) {
3584
- 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' ] } } );
3585
- }
3586
- }
3587
- }
3716
+ let actionType = 'deleteOpenUsers';
3717
+ let teamsMsg;
3718
+ let teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
3719
+ teamsMsg = 'ClientId: '+ insertdata.client_id + ', Action: '+ actionType + ', ChecklistId: '+ getCLconfig._id + ', Checklist Name: '+ getCLconfig.checkListName;
3720
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
3588
3721
 
3589
3722
  let inprogressData = await processedchecklist.find( {
3590
3723
  date_string: insertdata.date_string,
@@ -3595,6 +3728,12 @@ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedche
3595
3728
  }, { userId: 1, store_id: 1 } );
3596
3729
 
3597
3730
  if ( inprogressData.length ) {
3731
+ inprogressData.forEach( ( item ) => {
3732
+ let checkData = assignUserList.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
3733
+ if ( !checkData ) {
3734
+ deletedList.push( item._id );
3735
+ }
3736
+ } );
3598
3737
  assignUserList = assignUserList.filter( ( item ) => {
3599
3738
  let findData = inprogressData.find( ( ele ) => ele.userId.toString() == item.userId.toString() && ele.store_id == item.store_id );
3600
3739
  if ( !findData ) {
@@ -3603,11 +3742,15 @@ async function insertPCBulkV4( getCLconfig, checklistId, currentdate, updatedche
3603
3742
  } );
3604
3743
  }
3605
3744
 
3606
- await processedchecklist.deleteMany( { date_string: insertdata.date_string,
3607
- date_iso: insertdata.date_iso,
3608
- client_id: insertdata.client_id,
3609
- checkListId: updatedchecklist._id, checklistStatus: 'open' } );
3745
+ if ( deletedList.length ) {
3746
+ await processedchecklist.deleteMany( { date_string: insertdata.date_string, date_iso: insertdata.date_iso, client_id: insertdata.client_id, checkListId: updatedchecklist._id, _id: { $in: deletedList } } );
3747
+ }
3610
3748
  await processedchecklist.insertMany( assignUserList );
3749
+ actionType = 'insertAssignUsers';
3750
+ teamsMsg;
3751
+ teamsAlertUrls = process.env.teamsAlertURL ? JSON.parse( process.env.teamsAlertURL ) : '';
3752
+ teamsMsg = 'ClientId: '+ insertdata.client_id + ', Action: '+ actionType + ', ChecklistId: '+ getCLconfig._id + ', Checklist Name: '+ getCLconfig.checkListName + ', assignedUserCount:'+ assignUserList.length+', inprogressSubmitCount:' + submittedDetails?.length;
3753
+ sendTeamsNotification( teamsAlertUrls.checklist, teamsMsg );
3611
3754
  }
3612
3755
 
3613
3756
  tokenList.forEach( ( item ) => {
@@ -3682,11 +3825,11 @@ async function updateOpenSearch( user, data ) {
3682
3825
  export const aiChecklist = async ( req, res ) => {
3683
3826
  try {
3684
3827
  let storeDetails = await storeService.count( { clientId: req.query.clientId, status: 'active' } );
3685
- let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum' ];
3828
+ let aiList = [ 'mobileusagedetection', 'storeopenandclose', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended', 'eyetest', 'remoteoptometrist', 'storehygienemonitoring', 'queuealert', 'cleaning', 'scrum', 'suspiciousactivity', 'boxalert', 'suspiciousfootfall', 'drinking', 'bagdetection' ];
3686
3829
  let checklistDetails = [];
3687
3830
  let publishList = [];
3688
3831
  let unpublishList = [];
3689
- publishList = await checklistService.find( { client_id: req.query.clientId, checkListType: { $in: aiList } }, { publish: 1, checkListName: 1, checkListType: 1, client_id: 1, checkListDescription: 1 } );
3832
+ 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 } );
3690
3833
  if ( publishList.length ) {
3691
3834
  let existList = publishList.map( ( item ) => item.checkListType );
3692
3835
  aiList = aiList.filter( ( item ) => !existList.includes( item ) );
@@ -3695,9 +3838,13 @@ export const aiChecklist = async ( req, res ) => {
3695
3838
  checklistDetails = [ ...publishList, ...unpublishList ];
3696
3839
 
3697
3840
  checklistDetails.forEach( ( item ) => {
3698
- item.storeCount = storeDetails;
3841
+ if ( ![ 'mobileusagedetection', 'storeopenandclose', 'cleaning', 'scrum', 'uniformdetection', 'staffleftinthemiddle', 'customerunattended' ].includes( item.checkListType ) ) {
3842
+ item.storeCount = storeDetails;
3843
+ }
3699
3844
  } );
3700
3845
 
3846
+ checklistDetails.sort( ( a, b ) => a.checkListName.localeCompare( b.checkListName ) );
3847
+
3701
3848
  return res.sendSuccess( checklistDetails );
3702
3849
  } catch ( e ) {
3703
3850
  logger.error( 'aiChecklist =>', e );
@@ -3889,6 +4036,8 @@ export const selectAssign = async ( req, res ) => {
3889
4036
  userEmail: { $arrayElemAt: [ '$spocDetails.email', 0 ] },
3890
4037
  contact: { $arrayElemAt: [ '$spocDetails.contact', 0 ] },
3891
4038
  city: '$storeProfile.city',
4039
+ openTime: '$storeProfile.open',
4040
+ closeTime: '$storeProfile.close',
3892
4041
  },
3893
4042
  },
3894
4043
 
@@ -4041,47 +4190,75 @@ export async function updateAssign( req, res ) {
4041
4190
  if ( !checklistDetails ) {
4042
4191
  return res.sendError( 'No data found', 204 );
4043
4192
  }
4193
+ let groupList = req.body.assignedGroup;
4044
4194
  req.body.assignedGroup = [ ...new Set( req.body.assignedGroup.map( ( item ) => item.id ) ) ];
4195
+ groupList = req.body.assignedGroup.reduce( ( acc, ele ) => {
4196
+ let findDetails = groupList.find( ( item ) => item.id == ele );
4197
+ if ( findDetails ) {
4198
+ acc.push( findDetails?.clusterName || findDetails?.teamName );
4199
+ };
4200
+ return acc;
4201
+ }, [] );
4045
4202
  // req.body.assignedGroup = req.body.assignedGroup.map( ( ele ) => {
4046
4203
  // return { id: ele };
4047
4204
  // } );
4048
4205
  let getAssignedDetails = await assignedService.find( { checkListId: req.body.checkListId } );
4206
+ let oldCoverage;
4049
4207
  if ( getAssignedDetails.length ) {
4050
- if ( req.body.coverage == 'store' ) {
4051
- getAssignedDetails = [ ...new Set( getAssignedDetails.map( ( ele ) => ele.storeName ) ) ];
4052
- } else {
4053
- getAssignedDetails = [ ...new Set( getAssignedDetails.map( ( ele ) => ele.userName ) ) ];
4054
- }
4208
+ oldCoverage = getAssignedDetails?.[0]?.coverage;
4209
+ let storeClusterDetails = getAssignedDetails.filter( ( ele ) => ele?.storeName || ele?.clusterName );
4210
+ let userTeamDetails = getAssignedDetails.filter( ( ele ) => !ele?.storeName && ( ele?.userName || ele?.teamName ) );
4211
+ storeClusterDetails = [ ...new Set( storeClusterDetails.map( ( ele ) => ele?.storeName || ele?.clusterName ) ) ];
4212
+ userTeamDetails= [ ...new Set( userTeamDetails.map( ( ele ) => ele?.userName || ele?.teamName ) ) ];
4213
+ getAssignedDetails = [ ...storeClusterDetails, ...userTeamDetails ];
4055
4214
  }
4056
-
4057
- let added = req.body.assignedList.filter( ( item ) => {
4215
+ let assignedAllList = [ ...req.body.assignedList, ...groupList ];
4216
+ let added = assignedAllList.filter( ( item ) => {
4058
4217
  let storeUsername;
4218
+ let clusterTeamName;
4059
4219
  if ( req.body.coverage == 'store' ) {
4060
- storeUsername = item.storeName;
4220
+ if ( item?.storeName ) {
4221
+ storeUsername = item?.storeName;
4222
+ } else {
4223
+ clusterTeamName = item;
4224
+ }
4061
4225
  } else {
4062
- storeUsername = item.userName;
4226
+ if ( item?.userName ) {
4227
+ storeUsername = item?.userName;
4228
+ } else {
4229
+ clusterTeamName = item;
4230
+ }
4063
4231
  }
4064
- if ( !getAssignedDetails.includes( storeUsername ) ) {
4232
+ if ( !getAssignedDetails.includes( storeUsername ) && !getAssignedDetails.includes( clusterTeamName ) ) {
4065
4233
  return item;
4066
4234
  }
4067
4235
  } ).map( ( ele ) => {
4068
4236
  if ( req.body.coverage == 'store' ) {
4069
- return ele.storeName;
4237
+ return ele?.storeName || ele;
4070
4238
  } else {
4071
- return ele.userName;
4239
+ return ele?.userName || ele;
4072
4240
  }
4073
4241
  } );
4074
4242
  let removed = getAssignedDetails.filter( ( item ) => {
4075
4243
  let list;
4076
4244
  if ( req.body.coverage == 'store' ) {
4077
- list = req.body.assignedList.map( ( item ) => item.storeName );
4245
+ list = assignedAllList.map( ( item ) => item?.storeName );
4246
+ let clusterList = assignedAllList.filter( ( item ) => !item?.storeName );
4247
+ list = [ ...list, ...clusterList ];
4078
4248
  } else {
4079
- list = req.body.assignedList.map( ( item ) => item.userName ); ;
4249
+ list = assignedAllList.map( ( item ) => item.userName );
4250
+ let teamList = assignedAllList.filter( ( item ) => !item?.userName );
4251
+ list = [ ...list, ...teamList ];
4080
4252
  }
4081
4253
  if ( !list.includes( item ) ) {
4082
4254
  return item;
4083
4255
  }
4084
4256
  } );
4257
+ if ( getAssignedDetails.length ) {
4258
+ removed = { user: oldCoverage == 'user' ? removed : [], store: oldCoverage == 'store' ? removed : [] };
4259
+ } else {
4260
+ removed = { user: [], store: [] };
4261
+ }
4085
4262
 
4086
4263
  await assignedService.deleteMany( { checkListId: req.body.checkListId } );
4087
4264
  let assignedUserList = [];
@@ -4100,7 +4277,7 @@ export async function updateAssign( req, res ) {
4100
4277
  },
4101
4278
  ];
4102
4279
  let assignUserDetails = await userService.aggregate( query );
4103
- await Promise.all( req.body.assignedList.map( async ( assign ) => {
4280
+ for ( let assign of req.body.assignedList ) {
4104
4281
  let userDetails = assignUserDetails.find( ( ele ) => ele.email.toLowerCase() == assign.userEmail.toLowerCase() );
4105
4282
  if ( !userDetails ) {
4106
4283
  let userData = {
@@ -4110,7 +4287,7 @@ export async function updateAssign( req, res ) {
4110
4287
  clientId: req.body.clientId,
4111
4288
  };
4112
4289
  userDetails = await createUser( userData );
4113
- userDetails = userDetails;
4290
+ assignUserDetails.push( userDetails );
4114
4291
  }
4115
4292
  let data = {
4116
4293
  ...assign,
@@ -4124,7 +4301,7 @@ export async function updateAssign( req, res ) {
4124
4301
  };
4125
4302
  delete data._id;
4126
4303
  assignedUserList.push( data );
4127
- } ) );
4304
+ }
4128
4305
  let assignGroupDetails = [];
4129
4306
  if ( req.body.coverage == 'store' ) {
4130
4307
  assignGroupDetails = await clusterServices.findcluster( { _id: { $in: req.body.assignedGroup } } );
@@ -4152,3 +4329,225 @@ export async function updateAssign( req, res ) {
4152
4329
  return res.sendError( e, 500 );
4153
4330
  }
4154
4331
  }
4332
+
4333
+ export async function updateAiConfigure( req, res ) {
4334
+ try {
4335
+ if ( !req.body.storeList.length && req.body.publish ) {
4336
+ return res.sendError( 'Please assign a store', 400 );
4337
+ }
4338
+ if ( !req.body.id && !req.body.type ) {
4339
+ return res.sendError( 'Type/Id is required', 400 );
4340
+ }
4341
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'global' && !req.body?.aiConfig?.events?.length ) {
4342
+ return res.sendError( 'Event is required', 400 );
4343
+ }
4344
+ let query;
4345
+ query = req.body.type ? { checkListType: req.body.type, client_id: { $exists: false } } : { _id: req.body.id, client_id: req.body.clientId };
4346
+ let aiChecklistDetails = await checklistService.findOne( query );
4347
+ if ( !aiChecklistDetails ) {
4348
+ return res.sendError( 'No data found', 204 );
4349
+ }
4350
+ let details = {
4351
+ checkListName: aiChecklistDetails.checkListName,
4352
+ checkListDescription: aiChecklistDetails.checkListDescription,
4353
+ client_id: req.body.clientId,
4354
+ publish: req.body.publish,
4355
+ aiConfig: req.body.aiConfig,
4356
+ ...( !req.body?.id ) ? { createdBy: req.user._id, createdByName: req.user.userName } : {},
4357
+ questionCount: 0,
4358
+ storeCount: req.body.storeList.length,
4359
+ type: 'checklist',
4360
+ checkListType: aiChecklistDetails.checkListType,
4361
+ schedule: 'daily',
4362
+ ...( req.body.publish ) ? { publishDate: new Date() } :{},
4363
+ approver: req.body?.approver || [],
4364
+ scheduleRepeatedDay: [ '01' ],
4365
+ scheduleStartTime: '06:00 AM',
4366
+ scheduleEndTime: '11:59 PM',
4367
+ enableNewDeployedStore: req.body.enableNewDeployedStore,
4368
+ checkListNumber: aiChecklistDetails?.checkListNumber || 1,
4369
+ };
4370
+ let aiResponse = await checklistService.updateOne( { checkListType: aiChecklistDetails.checkListType, client_id: req.body.clientId }, details );
4371
+ let checklistId = req.body?.id || aiResponse?.upsertedId;
4372
+ if ( req.body?.approver ) {
4373
+ let data = [];
4374
+ let existEmail = await traxApprover.find( { checkListId: checklistId, isDeleted: false } );
4375
+ let mailList = existEmail.map( ( item ) => item.userEmail );
4376
+ existEmail = req.body?.approver.filter( ( item ) => mailList.includes( item.value ) ).map( ( item ) => item.value );
4377
+ let userMailList = req.body?.approver.map( ( ele ) => ele.value );
4378
+ req.body?.approver.forEach( ( ele ) => {
4379
+ if ( !existEmail.includes( ele.value ) ) {
4380
+ data.push( {
4381
+ userEmail: ele.value,
4382
+ checkListId: checklistId,
4383
+ type: 'checklist',
4384
+ checkListName: aiChecklistDetails.checkListName,
4385
+ client_id: req.body.clientId,
4386
+ } );
4387
+ }
4388
+ } );
4389
+
4390
+ await traxApprover.updateMany( { checkListId: checklistId, userEmail: { $nin: userMailList } }, { isDeleted: true } );
4391
+ if ( data.length ) {
4392
+ await traxApprover.insertMany( data );
4393
+ }
4394
+ }
4395
+ if ( req.body.storeList ) {
4396
+ let storeData = [];
4397
+ req.body.storeList.forEach( ( ele ) => {
4398
+ let eventTime = [];
4399
+ Object.keys( ele ).forEach( ( key ) => {
4400
+ let keyValue ={};
4401
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'store' && key.includes( 'startTime' ) ) {
4402
+ let num = key.slice( -1 );
4403
+ if ( ele[key] && ele[`configTime${num}`] ) {
4404
+ keyValue['time'] = ele[key];
4405
+ keyValue['duration'] = ele[`configTime${num}`];
4406
+ eventTime.push( keyValue );
4407
+ }
4408
+ }
4409
+ } );
4410
+ if ( req.body.aiConfig?.assignConfig && req.body.aiConfig?.assignConfig == 'global' ) {
4411
+ req.body.aiConfig.events.forEach( ( event ) => {
4412
+ if ( event.time.split( ':' ).length <= 2 ) {
4413
+ event.time = event.time + ':00';
4414
+ }
4415
+ } );
4416
+ eventTime = req.body.aiConfig.events;
4417
+ }
4418
+ storeData.push( {
4419
+ storeName: ele.storeName,
4420
+ ...( req.body.aiConfig?.assignConfig ) ? { events: eventTime } : { events: [] },
4421
+ checkListId: checklistId,
4422
+ client_id: req.body.clientId,
4423
+ checkListName: aiChecklistDetails.checkListName,
4424
+ store_id: ele.storeId,
4425
+ assignId: ele._id,
4426
+ } );
4427
+ } );
4428
+ await assignedService.deleteMany( { checkListId: checklistId } );
4429
+ await assignedService.insertMany( storeData );
4430
+ if ( req.body.publish ) {
4431
+ let processedData = {
4432
+ client_id: req.body.clientId,
4433
+ date_iso: new Date( dayjs().format( 'YYYY-MM-DD' ) ),
4434
+ date_string: dayjs().format( 'YYYY-MM-DD' ),
4435
+ sourceCheckList_id: checklistId,
4436
+ checkListName: aiChecklistDetails.checkListName,
4437
+ checkListDescription: aiChecklistDetails.checkListDescription,
4438
+ scheduleStartTime: '06:00 AM',
4439
+ scheduleEndTime: '11:59 PM',
4440
+ scheduleStartTime_iso: dayjs.utc( '06:00 AM', 'hh:mm A' ).format(),
4441
+ scheduleEndTime_iso: dayjs.utc( '11:59 PM', 'hh:mm A' ).format(),
4442
+ allowedOverTime: false,
4443
+ allowedStoreLocation: false,
4444
+ createdBy: req.user._id,
4445
+ createdByName: req.user.userName,
4446
+ questionAnswers: [],
4447
+ isdeleted: false,
4448
+ questionCount: 0,
4449
+ storeCount: req.body.storeList.length,
4450
+ publishDate: details?.publishDate,
4451
+ locationCount: 1,
4452
+ checkListType: aiChecklistDetails.checkListType,
4453
+ scheduleRepeatedType: 'daily',
4454
+ aiStoreList: storeData.length? storeData.map( ( store ) => {
4455
+ return { storeName: store.storeName, events: store.events, storeId: store.store_id };
4456
+ } ) : [],
4457
+ aiConfig: req.body.aiConfig,
4458
+ approver: req.body?.approver || [],
4459
+ };
4460
+ let configResponse = await processedchecklistConfig.updateOne( { date_string: dayjs().format( 'YYYY-MM-DD' ), sourceCheckList_id: checklistId, checkListType: aiChecklistDetails.checkListType }, processedData );
4461
+ let data = {
4462
+ ...( configResponse?.upsertedId ) ? { checkListId: configResponse?.upsertedId } : {},
4463
+ checkListName: aiChecklistDetails.checkListName,
4464
+ checkListDescription: aiChecklistDetails.checkListDescription,
4465
+ date_iso: new Date( dayjs().format( 'YYYY-MM-DD' ) ),
4466
+ date_string: dayjs().format( 'YYYY-MM-DD' ),
4467
+ allowedOverTime: false,
4468
+ allowedStoreLocation: false,
4469
+ scheduleStartTime: '06:00 AM',
4470
+ scheduleStartTime_iso: dayjs.utc( '06:00 AM', 'hh:mm A' ).format(),
4471
+ scheduleEndTime: '11:59 PM',
4472
+ scheduleEndTime_iso: dayjs.utc( '11:59 PM', 'hh:mm A' ).format(),
4473
+ createdBy: req.user._id,
4474
+ createdByName: req.user.userName,
4475
+ sourceCheckList_id: checklistId,
4476
+ checkListType: aiChecklistDetails.checkListType,
4477
+ storeCount: storeData.length,
4478
+ questionCount: 0,
4479
+ publishDate: new Date(),
4480
+ locationCount: 0,
4481
+ scheduleRepeatedType: 'daily',
4482
+ client_id: req.body.clientId,
4483
+ aiStoreList: storeData?.length ? storeData.map( ( store ) => store.store_id ) : [],
4484
+ approvalEnable: req.body?.approver.length ? true : false,
4485
+ };
4486
+ await processedchecklist.updateOne( { date_string: dayjs().format( 'YYYY-MM-DD' ), sourceCheckList_id: checklistId, checkListType: aiChecklistDetails.checkListType }, data );
4487
+ }
4488
+ }
4489
+ return res.sendSuccess( 'Checklist updated successfully' );
4490
+ } catch ( e ) {
4491
+ logger.error( { functionName: 'updateAiConfigure', error: e } );
4492
+ return res.sendError( e, 500 );
4493
+ }
4494
+ }
4495
+
4496
+
4497
+ export async function getAiDetails( req, res ) {
4498
+ try {
4499
+ let storeList = [];
4500
+ if ( !req.query.id && !req.query.type ) {
4501
+ return res.sendError( 'Type/Id is required', 400 );
4502
+ }
4503
+ let query = req.query.type ? { checkListType: req.query.type, client_id: { $exists: false } } : { _id: req.query.id, client_id: req.query.clientId };
4504
+ let checklistDetails = await checklistService.findOne( query );
4505
+ if ( !checklistDetails ) {
4506
+ return res.sendError( 'No data found', 204 );
4507
+ }
4508
+ let clientDetails = await clientService.findOne( { clientId: req.query.clientId }, { 'planDetails.product': 1 } );
4509
+ if ( !clientDetails ) {
4510
+ return res.sendError( 'No data found', 204 );
4511
+ }
4512
+ if ( req.query?.id ) {
4513
+ storeList = await assignedService.find( { checkListId: req.query?.id } );
4514
+ let data = [];
4515
+ await Promise.all( ( storeList.map( async ( ele ) => {
4516
+ let element = {};
4517
+ element['storeName'] = ele.storeName,
4518
+ element['storeId'] = ele.store_id;
4519
+ element['_id'] = ele.assignId;
4520
+ let getStoreDetails = await storeService.findOne( { storeId: ele.store_id, status: 'active', clientId: req.query.clientId } );
4521
+ if ( getStoreDetails ) {
4522
+ element['openTime'] = getStoreDetails?.storeProfile?.open;
4523
+ element['closeTime'] = getStoreDetails?.storeProfile?.close;
4524
+ }
4525
+ if ( [ 'cleaning', 'scrum' ].includes( checklistDetails.checkListType ) && checklistDetails?.aiConfig?.assignConfig == 'store' ) {
4526
+ ele.events.forEach( ( event, index ) => {
4527
+ element[`startTime${index+1}`] = event.time;
4528
+ element[`configTime${index+1}`] = event.duration;
4529
+ } );
4530
+ }
4531
+ data.push( element );
4532
+ } ) ) );
4533
+ storeList = data;
4534
+ }
4535
+
4536
+ let response = {
4537
+ checkListName: checklistDetails?.checkListName,
4538
+ checkListDescription: checklistDetails?.checkListDescription,
4539
+ publish: checklistDetails?.publish,
4540
+ aiConfig: checklistDetails?.aiConfig,
4541
+ storeList: storeList,
4542
+ approver: checklistDetails?.approver,
4543
+ storeCount: checklistDetails?.storeCount,
4544
+ ...( checklistDetails?.client_id ) ? { clientId: checklistDetails?.client_id } :{},
4545
+ enableNewDeployedStore: checklistDetails?.enableNewDeployedStore,
4546
+ product: clientDetails?.planDetails?.product.map( ( product ) => product.productName ),
4547
+ };
4548
+ return res.sendSuccess( response );
4549
+ } catch ( e ) {
4550
+ logger.error( { functionName: getAiDetails, error: e } );
4551
+ return res.sendError( e, 500 );
4552
+ }
4553
+ }