tango-app-api-task 3.4.0-flag-2 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tango-app-api-task",
3
- "version": "3.4.0-flag-2",
3
+ "version": "3.4.1-activitylog-1",
4
4
  "description": "Task",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -176,13 +176,9 @@ export async function createUpdateTask( req, res ) {
176
176
  }, {} );
177
177
  }
178
178
 
179
- console.log( inputBody.sections );
180
179
  getExistQuestions.forEach( ( ele ) => {
181
180
  ele.question.forEach( ( qn ) => {
182
- console.log( qn );
183
- console.log( JSON.stringify( inputBody.sections[0].questions ) );
184
181
  let question = inputBody.sections[0].questions.find( ( qns ) => qns.oldQname === qn.qname );
185
- console.log( question, 'tion' );
186
182
  if ( question ) {
187
183
  qn.answers.forEach( ( ans ) => {
188
184
  delete ans.answeroptionNumber;
@@ -191,8 +187,8 @@ export async function createUpdateTask( req, res ) {
191
187
  delete ans.answeroptionNumber;
192
188
  } );
193
189
  let compare = findDifferences( qn, question );
194
- if ( Object.keys( compare ).length && ( compare?.answerType || compare?.answers || compare?.linkType || compare?.qname) ) {
195
- questionList.questionEdit.push( { sectionName: ele.section, questions: [ { previous: qn ,new: question} ] } );
190
+ if ( Object.keys( compare ).length ) {
191
+ questionList.questionEdit.push( { sectionName: ele.section, questions: [ { previous: qn, new: question } ] } );
196
192
  }
197
193
  } else {
198
194
  let sectionIndex = questionList.questionDelete.findIndex( ( sec ) => sec.sectionName === ele.section );
@@ -273,6 +269,25 @@ export async function createUpdateTask( req, res ) {
273
269
  };
274
270
  await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
275
271
  }
272
+
273
+ if ( inputBody?.submitType == 'save' ) {
274
+ let logObj = {
275
+ client_id: inputBody.clientId,
276
+ createAt: new Date(),
277
+ sourceCheckList_id: inputBody._id,
278
+ checkListName: inputBody.checklistName,
279
+ fromCheckListName: '',
280
+ type: 'task',
281
+ action: 'draft',
282
+ storeName: '',
283
+ store_id: '',
284
+ createdByEmail: req.user.email,
285
+ createdBy: req.user.userName,
286
+ coverage: 'store',
287
+ logDetails: {},
288
+ };
289
+ await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
290
+ }
276
291
  return res.sendSuccess( { checklistId: checkListId, message: message } );
277
292
  } else {
278
293
  return res.sendError( { message: 'something went wrong' }, 500 );
@@ -659,14 +674,14 @@ export const validateUserv1 = async ( req, res ) => {
659
674
  {
660
675
  $project: {
661
676
  newEmail: { $toLower: '$email' },
662
- isActive: 1,
677
+ // isActive: 1,
663
678
  clientId: 1,
664
679
  },
665
680
  },
666
681
  {
667
682
  $match: {
668
683
  newEmail: { $in: userEmailList },
669
- isActive: true,
684
+ // isActive: true,
670
685
  clientId: { $ne: req.body.clientId },
671
686
  },
672
687
  },
@@ -707,7 +722,7 @@ export const validateUserv1 = async ( req, res ) => {
707
722
  let newStoreList = storeList.filter( ( ele ) => ele != null && !existsStore.includes( ele.toLowerCase() ) );
708
723
  if ( req.body.coverage == 'store' ) {
709
724
  assignDetails.forEach( ( item ) => {
710
- let getStoreDetails = storeDetails.find( ( store ) => store.storeName.toLowerCase() == item.storeName.toLowerCase() );
725
+ let getStoreDetails = storeDetails.find( ( store ) => store.storeName.toLowerCase() == item.storeName.trim().toLowerCase() );
711
726
  if ( getStoreDetails ) {
712
727
  let storeUserDetails = userDetails.find( ( ele ) => ele.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
713
728
  item._id = getStoreDetails._id;
@@ -728,6 +743,11 @@ export const validateUserv1 = async ( req, res ) => {
728
743
  } );
729
744
  }
730
745
 
746
+ newStoreList = [ ...new Set( newStoreList.map( ( item ) => item ) ) ];
747
+ newUserList = [ ...new Set( newUserList.map( ( item ) => item ) ) ];
748
+ existEmail = [ ...new Set( existEmail.map( ( item ) => item ) ) ];
749
+ inActiveStores = [ ...new Set( inActiveStores.map( ( item ) => item ) ) ];
750
+
731
751
  if ( ( newUserList.length || newStoreList.length || existEmail.length || inActiveStores.length ) && !req.body?.addUser ) {
732
752
  return res.sendError( { validate: false, user: newUserList, store: newStoreList, existEmail, inActiveStores, data: assignDetails }, 400 );
733
753
  }
@@ -1001,7 +1021,7 @@ export async function taskConfig( req, res ) {
1001
1021
  await checklistLogs.create( logInsertData );
1002
1022
 
1003
1023
  checklistDetails = await taskService.findOne( { _id: inputBody._id, isdeleted: false, client_id: inputBody.clientId } );
1004
-
1024
+ let oldPublish = checklistDetails.publish;
1005
1025
  if ( !checklistDetails ) {
1006
1026
  return res.sendError( 'No data found', 204 );
1007
1027
  }
@@ -1081,13 +1101,19 @@ export async function taskConfig( req, res ) {
1081
1101
  checklistDetails.scheduleEndTimeISO = checklistDetails?.scheduleEndTime ? dayjs.utc( checklistDetails?.scheduleEndTime, 'hh:mm A' ).format() : '';
1082
1102
  checklistDetails.scheduleDate = checklistDetails.scheduleDate ? dayjs.utc( checklistDetails?.scheduleDate ).format( 'YYYY-MM-DD' ) : '';
1083
1103
  configDetails.scheduleDate = configDetails.scheduleDate ? dayjs( configDetails?.scheduleDate ).format( 'YYYY-MM-DD' ) : '';
1084
- let removedKeys = [ 'publish', 'publishDate', 'storeCount', 'sections', 'createdAt', 'updatedAt', 'scheduleEndTimeISO' ];
1104
+ let removedKeys = [ 'clientId', 'submitType', 'removedUsers', 'publish', 'assignedUsers', 'added', 'removed', 'publishDate', 'scheduleEndTimeISO', 'storeCount' ];
1085
1105
  removedKeys.forEach( ( item ) => {
1086
1106
  delete checklistDetails?.[item];
1087
1107
  delete configDetails?.[item];
1088
1108
  } );
1089
- let differences = findObjectDifference( checklistDetails, configDetails );
1090
- if ( Object.keys( differences ).length || inputBody.added.length || inputBody.removed.length ) {
1109
+ let differences = findObjectDifference( configDetails, checklistDetails );
1110
+ if ( Object.keys( differences ).length || inputBody.added.length || req.body.removed?.user?.length || req.body.removed?.store?.length ) {
1111
+ let showSchedule = false;
1112
+ let scheduleKeys = [ 'scheduleDate', 'priorityType', 'scheduleEndTime' ];
1113
+
1114
+ if ( scheduleKeys.some( ( key ) => differences?.[key] ) ) {
1115
+ showSchedule = true;
1116
+ }
1091
1117
  let insertData = {
1092
1118
  client_id: inputBody.clientId,
1093
1119
  createAt: new Date(),
@@ -1095,7 +1121,7 @@ export async function taskConfig( req, res ) {
1095
1121
  checkListName: checklistDetails.checkListName,
1096
1122
  fromCheckListName: '',
1097
1123
  type: 'task',
1098
- action: 'updated',
1124
+ action: inputBody.publish ? 'updated' : 'draft',
1099
1125
  storeName: '',
1100
1126
  store_id: '',
1101
1127
  createdByEmail: req.user.email,
@@ -1104,14 +1130,14 @@ export async function taskConfig( req, res ) {
1104
1130
  logDetails: {
1105
1131
  schedule: {
1106
1132
  previous: {
1107
- ...( differences?.scheduleDate && ( differences?.scheduleDate.previous != '' && differences?.scheduleDate.previous != null ) ) ? { scheduleDate: checklistDetails?.scheduleDate } :{},
1108
- time: differences?.scheduleEndTime ? checklistDetails.scheduleEndTime : '',
1109
- priority: differences?.priorityType ? checklistDetails?.priorityType : '',
1133
+ ...( showSchedule ) ? { scheduleDate: checklistDetails?.scheduleDate } :{},
1134
+ time: showSchedule ? checklistDetails.scheduleEndTime : '',
1135
+ priority: showSchedule ? checklistDetails?.priorityType : '',
1110
1136
  },
1111
1137
  new: {
1112
- ...( differences?.scheduleDate && ( differences?.scheduleDate.new != '' && differences?.scheduleDate.new != null ) ) ? { scheduleDate: configDetails?.scheduleDate } :{},
1113
- time: differences?.scheduleEndTime ? configDetails.scheduleEndTime : '',
1114
- priority: differences?.priorityType ? configDetails?.priorityType : '',
1138
+ ...( showSchedule ) ? { scheduleDate: configDetails?.scheduleDate } :{},
1139
+ time: showSchedule ? configDetails.scheduleEndTime : '',
1140
+ priority: showSchedule ? configDetails?.priorityType : '',
1115
1141
  },
1116
1142
  },
1117
1143
  response: {
@@ -1123,35 +1149,36 @@ export async function taskConfig( req, res ) {
1123
1149
  ],
1124
1150
  },
1125
1151
  ...( differences?.approver ) ? { approver:
1126
- { previous: differences?.approver?.previous.map( ( item ) => item.name ).toString(),
1127
- new: differences?.approver?.new.map( ( item ) => item.name ).toString() },
1152
+ { previous: checklistDetails?.approver.map( ( item ) => item.name ).toString(),
1153
+ new: configDetails?.approver.map( ( item ) => item.name ).toString() },
1128
1154
  } : { approver: {} },
1129
1155
  owner: {},
1130
1156
  ...( inputBody.coverage == 'store' ) ? { storeAdded: inputBody.added } :{ storeAdded: [] },
1131
- ...( inputBody.coverage == 'store' ) ? { storeRemoved: inputBody.removed } :{ storeRemoved: [] },
1157
+ ...( req.body.removed.store.length ) ? { storeRemoved: inputBody.removed.store } :{ storeRemoved: [] },
1132
1158
  ...( inputBody.coverage == 'user' ) ? { userAdded: inputBody.added } :{ userAdded: [] },
1133
- ...( inputBody.coverage == 'user' ) ? { userRemoved: inputBody.removed } :{ userRemoved: [] },
1159
+ ...( req.body.removed.user.length ) ? { userRemoved: inputBody.removed.user } :{ userRemoved: [] },
1134
1160
  },
1135
1161
  };
1136
1162
  await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertData );
1137
1163
  }
1138
-
1139
- let logObj = {
1140
- client_id: inputBody.client_id,
1141
- createAt: new Date(),
1142
- sourceCheckList_id: inputBody._id,
1143
- checkListName: checklistDetails.checkListName,
1144
- fromCheckListName: '',
1145
- type: 'task',
1146
- action: inputBody.publish ? 'published' : 'unpublished',
1147
- storeName: '',
1148
- store_id: '',
1149
- createdByEmail: req.user.email,
1150
- createdBy: req.user.userName,
1151
- coverage: inputBody.coverage,
1152
- logDetails: {},
1153
- };
1154
- await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1164
+ if ( inputBody.publish != oldPublish || inputBody?.publish ) {
1165
+ let logObj = {
1166
+ client_id: inputBody.client_id,
1167
+ createAt: new Date(),
1168
+ sourceCheckList_id: inputBody._id,
1169
+ checkListName: checklistDetails.checkListName,
1170
+ fromCheckListName: '',
1171
+ type: 'task',
1172
+ action: inputBody.publish ? 'published' : 'unpublished',
1173
+ storeName: '',
1174
+ store_id: '',
1175
+ createdByEmail: req.user.email,
1176
+ createdBy: req.user.userName,
1177
+ coverage: inputBody.coverage,
1178
+ logDetails: {},
1179
+ };
1180
+ await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
1181
+ }
1155
1182
  return res.sendSuccess( { id: inputBody._id, message: message } );
1156
1183
  }
1157
1184
  } catch ( e ) {
@@ -1742,7 +1769,60 @@ export async function reinitiateTask( req, res ) {
1742
1769
  await taskProcessedService.insert( userTaskData );
1743
1770
  }
1744
1771
  }
1772
+ let differences = findObjectDifference( req.body, taskDetails );
1773
+ if ( Object.keys( differences ).length ) {
1774
+ let showSchedule = false;
1775
+ let scheduleKeys = [ 'scheduleDate', 'priorityType', 'scheduleEndTime' ];
1776
+
1777
+ if ( scheduleKeys.some( ( key ) => differences?.[key] ) ) {
1778
+ showSchedule = true;
1779
+ }
1745
1780
 
1781
+ let insertData = {
1782
+ client_id: taskDetails.client_id,
1783
+ createAt: new Date(),
1784
+ sourceCheckList_id: taskDetails._id,
1785
+ checkListName: taskDetails.checkListName,
1786
+ fromCheckListName: '',
1787
+ type: 'task',
1788
+ action: 'updated',
1789
+ storeName: '',
1790
+ store_id: '',
1791
+ createdByEmail: req.user.email,
1792
+ createdBy: req.user.userName,
1793
+ coverage: taskDetails.coverage,
1794
+ logDetails: {
1795
+ schedule: {
1796
+ previous: {
1797
+ ...( showSchedule ) ? { scheduleDate: taskDetails?.scheduleDate } :{},
1798
+ time: showSchedule ? taskDetails.scheduleEndTime : '',
1799
+ priority: showSchedule ? taskDetails?.priorityType : '',
1800
+ },
1801
+ new: {
1802
+ ...( showSchedule ) ? { scheduleDate: req.body?.scheduleDate } :{},
1803
+ time: showSchedule ? req.body.scheduleEndTime : '',
1804
+ priority: showSchedule ? req.body?.priorityType : '',
1805
+ },
1806
+ },
1807
+ response: {
1808
+ previous: [
1809
+ ...( differences?.allowedStoreLocation && taskDetails.allowedStoreLocation ? [ 'Geo fencing' ] : [] ),
1810
+ ],
1811
+ new: [
1812
+ ...( differences?.allowedStoreLocation && req.body.allowedStoreLocation ? [ 'Geo fencing' ] : [] ),
1813
+ ],
1814
+ },
1815
+ approver: { previous: taskDetails?.approver.map( ( item ) => item.name ).toString(),
1816
+ new: taskDetails?.approver.map( ( item ) => item.name ).toString() },
1817
+ owner: {},
1818
+ storeAdded: [],
1819
+ storeRemoved: [],
1820
+ userAdded: [],
1821
+ userRemoved: [],
1822
+ },
1823
+ };
1824
+ await insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, insertData );
1825
+ }
1746
1826
  return res.sendSuccess( 'Task reinitaite SUccessfully' );
1747
1827
  } catch ( e ) {
1748
1828
  logger.error( { functionName: 'reinitiateTask', error: e } );
@@ -1906,7 +1986,6 @@ export async function createChecklistTask( req, res ) {
1906
1986
  section_id: inputBody.sectionId,
1907
1987
  qno: inputBody.qno,
1908
1988
  parentQuestion: inputBody.parentQuestion,
1909
- uniqueNo: inputBody.uniqueNo,
1910
1989
  },
1911
1990
  'upsert': {
1912
1991
  taskId: String( response?._id ),
@@ -1934,11 +2013,11 @@ export async function createChecklistTask( req, res ) {
1934
2013
  let logData= {
1935
2014
  'client_id': inputBody.clientId,
1936
2015
  'createAt': new Date(),
1937
- 'sourceCheckList_id': taskDetails.sourceCheckList_id,
2016
+ 'sourceCheckList_id': response._id,
1938
2017
  'checkListName': inputBody.checkListName,
1939
2018
  'fromCheckListName': taskDetails.checkListName,
1940
2019
  'type': 'task',
1941
- 'action': 'created',
2020
+ 'action': 'task_created',
1942
2021
  'store_id': storeDetails?.storeId?storeDetails.storeId:'',
1943
2022
  'storeName': inputBody?.storeName?inputBody?.storeName:'',
1944
2023
  'createdByEmail': req.user.email,
@@ -1956,6 +2035,7 @@ export async function createChecklistTask( req, res ) {
1956
2035
  return res.sendSuccess( 'Task created successfully' );
1957
2036
  }
1958
2037
  } catch ( e ) {
2038
+ // console.log( 'e', e );
1959
2039
  logger.error( { functionName: 'createChecklistTask', error: e, message: req.body } );
1960
2040
  return res.sendError( e, 500 );
1961
2041
  }
@@ -1964,7 +2044,7 @@ export async function createChecklistTask( req, res ) {
1964
2044
  export async function createChecklistMultiTask( req, res ) {
1965
2045
  try {
1966
2046
  let inputBody = req.body;
1967
- console.log( inputBody );
2047
+ // console.log( inputBody );
1968
2048
  let inputData= inputBody.coverage==='user'?inputBody.userEmail:inputBody.storeName;
1969
2049
  let userDetailList;
1970
2050
  for ( let user of inputData ) {
@@ -2152,11 +2232,11 @@ export async function createChecklistMultiTask( req, res ) {
2152
2232
  let logData= {
2153
2233
  'client_id': inputBody.clientId,
2154
2234
  'createAt': new Date(),
2155
- 'sourceCheckList_id': taskDetails.sourceCheckList_id,
2235
+ 'sourceCheckList_id': response._id,
2156
2236
  'checkListName': inputBody.checkListName,
2157
2237
  'fromCheckListName': taskDetails.checkListName,
2158
2238
  'type': 'task',
2159
- 'action': 'created',
2239
+ 'action': 'task_created',
2160
2240
  'store_id': storeDetails?.storeId?storeDetails.storeId:'',
2161
2241
  'storeName': originaldata?.storeName?originaldata?.storeName:'',
2162
2242
  'createdByEmail': req.user.email,
@@ -2190,7 +2270,7 @@ export async function approveTask( req, res ) {
2190
2270
  if ( req.body?.storeId?.length ) {
2191
2271
  query['store_id'] = { $in: req.body.storeId };
2192
2272
  }
2193
- let taskDetails = await taskProcessedService.find( query, { _id: 1, checklistStatus: 1, storeName: 1, store_id: 1, userEmail: 1 } );
2273
+ let taskDetails = await taskProcessedService.find( query, { _id: 1, checklistStatus: 1, storeName: 1, store_id: 1, userEmail: 1, client_id: 1, coverage: 1, checkListName: 1 } );
2194
2274
  if ( !taskDetails.length ) {
2195
2275
  return res.sendError( 'No data found', 204 );
2196
2276
  }
@@ -2199,7 +2279,7 @@ export async function approveTask( req, res ) {
2199
2279
  let updateResponse = await taskProcessedService.updateMany( { _id: { $in: idList } }, { approvalStatus: true } );
2200
2280
  if ( updateResponse.modifiedCount || updateResponse.matchedCount ) {
2201
2281
  let inputstores = taskDetails.filter( ( data ) => data.checklistStatus == 'submit' );
2202
-
2282
+ let storeNames = inputstores.map( ( data ) => data.storeName );
2203
2283
  let params = {
2204
2284
  'payload': {
2205
2285
  sourceCheckList_id: req.body.sourceCheckList_id,
@@ -2212,8 +2292,6 @@ export async function approveTask( req, res ) {
2212
2292
  approvalStatus: true,
2213
2293
  },
2214
2294
  };
2215
-
2216
-
2217
2295
  const requestOptions = {
2218
2296
  method: 'POST',
2219
2297
  headers: {
@@ -2224,7 +2302,27 @@ export async function approveTask( req, res ) {
2224
2302
  let url = JSON.parse( process.env.LAMBDAURL );
2225
2303
 
2226
2304
  let searchResponse = await fetch( url.approveTask, requestOptions );
2227
-
2305
+ console.log( 'logData', logData );
2306
+ let logData= {
2307
+ 'client_id': taskDetails[0].client_id,
2308
+ 'createAt': new Date(),
2309
+ 'sourceCheckList_id': req.body.sourceCheckList_id,
2310
+ 'checkListName': taskDetails[0].checkListName,
2311
+ 'fromCheckListName': taskDetails[0].checkListName,
2312
+ 'type': 'checklist',
2313
+ 'action': 'approved',
2314
+ 'storeName': '',
2315
+ 'store_id': '',
2316
+ 'createdByEmail': req.user.email,
2317
+ 'createdBy': req.user._id,
2318
+ 'coverage': taskDetails[0].coverage,
2319
+ 'logDetails': {
2320
+ 'approved': storeNames,
2321
+ },
2322
+ };
2323
+ let urlopensearch = JSON.parse( process.env.OPENSEARCH );
2324
+ console.log( 'logData', logData );
2325
+ await insertOpenSearchData( urlopensearch.traxActivityLog, logData );
2228
2326
  if ( searchResponse.ok ) {
2229
2327
  let pendingstores = taskDetails.filter( ( data ) => data.checklistStatus != 'submit' );
2230
2328
  if ( pendingstores && pendingstores.length > 0 ) {
@@ -2413,7 +2511,7 @@ export async function redomultiTask( req, res ) {
2413
2511
  sectionId: originalData.section_id,
2414
2512
  sectionName: question[sectionIndex].sectionName,
2415
2513
  questionName: question[sectionIndex].questions[req.body.payload.qno - 1].qname,
2416
- action: 'redo',
2514
+ action: 'multiredo',
2417
2515
  store_id: taskDetails?.store_id?taskDetails?.store_id:'',
2418
2516
  storeName: taskDetails.storeName?taskDetails.storeName:'',
2419
2517
  client_id: taskDetails.client_id,
@@ -2972,6 +3070,22 @@ export const duplicateChecklist = async ( req, res ) => {
2972
3070
  sections.push( sectionDetails );
2973
3071
  }
2974
3072
  await taskQuestionService.insertMany( sections );
3073
+ let logObj = {
3074
+ client_id: checkDetails.client_id,
3075
+ createAt: new Date(),
3076
+ sourceCheckList_id: checkDetails._id,
3077
+ checkListName: checkDetails.checkListName,
3078
+ fromCheckListName: '',
3079
+ type: 'task',
3080
+ action: 'duplicated',
3081
+ storeName: '',
3082
+ store_id: '',
3083
+ createdByEmail: req.user.email,
3084
+ createdBy: req.user.userName,
3085
+ coverage: checkDetails.coverage,
3086
+ logDetails: {},
3087
+ };
3088
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
2975
3089
  return res.sendSuccess( { message: 'Task Duplicated Successfully' } );
2976
3090
  } else {
2977
3091
  return res.sendSuccess( { message: 'Duplicated Successfully' } );
@@ -3322,7 +3436,7 @@ export async function StoreHygienetask( req, res ) {
3322
3436
  return res.sendError( 'Maximum 3 referenceImage only allowed', 500 );
3323
3437
  }
3324
3438
  let data = {
3325
- checkListName: `${inputBody.taskName}(${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}-${inputBody.count})`,
3439
+ checkListName: `${inputBody.taskName}(${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}-${inputBody.zoneName?inputBody.zoneName:''})`,
3326
3440
  checkListDescription: inputBody.taskDescription,
3327
3441
  createdBy: creator[0]._id,
3328
3442
  createdByName: creator[0].userName,
@@ -4292,47 +4406,76 @@ export async function updateAssign( req, res ) {
4292
4406
  if ( !taskDetails ) {
4293
4407
  return res.sendError( 'No data found', 204 );
4294
4408
  }
4409
+ let groupList = req.body.assignedGroup;
4295
4410
  req.body.assignedGroup = [ ...new Set( req.body.assignedGroup.map( ( item ) => item.id ) ) ];
4411
+ groupList = req.body.assignedGroup.reduce( ( acc, ele ) => {
4412
+ let findDetails = groupList.find( ( item ) => item.id == ele );
4413
+ if ( findDetails ) {
4414
+ acc.push( findDetails?.clusterName || findDetails?.teamName );
4415
+ };
4416
+ return acc;
4417
+ }, [] );
4296
4418
  // req.body.assignedGroup = req.body.assignedGroup.map( ( ele ) => {
4297
4419
  // return { id: ele };
4298
4420
  // } );
4299
4421
  let getAssignedDetails = await taskAssignService.find( { checkListId: req.body.taskId } );
4422
+ let oldCoverage;
4300
4423
  if ( getAssignedDetails.length ) {
4301
- if ( req.body.coverage == 'store' ) {
4302
- getAssignedDetails = [ ...new Set( getAssignedDetails.map( ( ele ) => ele.storeName ) ) ];
4303
- } else {
4304
- getAssignedDetails = [ ...new Set( getAssignedDetails.map( ( ele ) => ele.userName ) ) ];
4305
- }
4424
+ oldCoverage = getAssignedDetails?.[0]?.coverage;
4425
+ let storeClusterDetails = getAssignedDetails.filter( ( ele ) => ele?.storeName || ele?.clusterName );
4426
+ let userTeamDetails = getAssignedDetails.filter( ( ele ) => !ele?.storeName && ( ele?.userName || ele?.teamName ) );
4427
+ storeClusterDetails = [ ...new Set( storeClusterDetails.map( ( ele ) => ele?.storeName || ele?.clusterName ) ) ];
4428
+ userTeamDetails= [ ...new Set( userTeamDetails.map( ( ele ) => ele?.userName || ele?.teamName ) ) ];
4429
+ getAssignedDetails = [ ...storeClusterDetails, ...userTeamDetails ];
4306
4430
  }
4307
4431
 
4308
- let added = req.body.assignedList.filter( ( item ) => {
4432
+ let assignedAllList = [ ...req.body.assignedList, ...groupList ];
4433
+ let added = assignedAllList.filter( ( item ) => {
4309
4434
  let storeUsername;
4435
+ let clusterTeamName;
4310
4436
  if ( req.body.coverage == 'store' ) {
4311
- storeUsername = item.storeName;
4437
+ if ( item?.storeName ) {
4438
+ storeUsername = item?.storeName;
4439
+ } else {
4440
+ clusterTeamName = item;
4441
+ }
4312
4442
  } else {
4313
- storeUsername = item.userName;
4443
+ if ( item?.userName ) {
4444
+ storeUsername = item?.userName;
4445
+ } else {
4446
+ clusterTeamName = item;
4447
+ }
4314
4448
  }
4315
- if ( !getAssignedDetails.includes( storeUsername ) ) {
4449
+ if ( !getAssignedDetails.includes( storeUsername ) && !getAssignedDetails.includes( clusterTeamName ) ) {
4316
4450
  return item;
4317
4451
  }
4318
4452
  } ).map( ( ele ) => {
4319
4453
  if ( req.body.coverage == 'store' ) {
4320
- return ele.storeName;
4454
+ return ele?.storeName || ele;
4321
4455
  } else {
4322
- return ele.userName;
4456
+ return ele?.userName || ele;
4323
4457
  }
4324
4458
  } );
4325
4459
  let removed = getAssignedDetails.filter( ( item ) => {
4326
4460
  let list;
4327
4461
  if ( req.body.coverage == 'store' ) {
4328
- list = req.body.assignedList.map( ( item ) => item.storeName );
4462
+ list = assignedAllList.map( ( item ) => item?.storeName );
4463
+ let clusterList = assignedAllList.filter( ( item ) => !item?.storeName );
4464
+ list = [ ...list, ...clusterList ];
4329
4465
  } else {
4330
- list = req.body.assignedList.map( ( item ) => item.userName ); ;
4466
+ list = assignedAllList.map( ( item ) => item.userName );
4467
+ let teamList = assignedAllList.filter( ( item ) => !item?.userName );
4468
+ list = [ ...list, ...teamList ];
4331
4469
  }
4332
4470
  if ( !list.includes( item ) ) {
4333
4471
  return item;
4334
4472
  }
4335
4473
  } );
4474
+ if ( getAssignedDetails.length ) {
4475
+ removed = { user: oldCoverage == 'user' ? removed : [], store: oldCoverage == 'store' ? removed : [] };
4476
+ } else {
4477
+ removed = { user: [], store: [] };
4478
+ }
4336
4479
  await taskAssignService.deleteMany( { checkListId: req.body.taskId } );
4337
4480
  let assignedUserList = [];
4338
4481
  let userEmailList = req.body.assignedList.map( ( ele ) => ele.userEmail.toLowerCase() );
@@ -4350,7 +4493,7 @@ export async function updateAssign( req, res ) {
4350
4493
  },
4351
4494
  ];
4352
4495
  let assignUserDetails = await userService.aggregate( query );
4353
- await Promise.all( req.body.assignedList.map( async ( assign ) => {
4496
+ for ( let assign of req.body.assignedList ) {
4354
4497
  let userDetails = assignUserDetails.find( ( ele ) => ele.email.toLowerCase() == assign.userEmail.toLowerCase() );
4355
4498
  if ( !userDetails ) {
4356
4499
  let userData = {
@@ -4360,6 +4503,7 @@ export async function updateAssign( req, res ) {
4360
4503
  clientId: req.body.clientId,
4361
4504
  };
4362
4505
  userDetails = await createUser( userData );
4506
+ assignUserDetails.push( userDetails );
4363
4507
  }
4364
4508
  let data = {
4365
4509
  ...assign,
@@ -4373,7 +4517,7 @@ export async function updateAssign( req, res ) {
4373
4517
  };
4374
4518
  delete data._id;
4375
4519
  assignedUserList.push( data );
4376
- } ) );
4520
+ }
4377
4521
  let assignGroupDetails = [];
4378
4522
  if ( req.body.coverage == 'store' ) {
4379
4523
  assignGroupDetails = await clusterServices.findcluster( { _id: { $in: req.body.assignedGroup } } );
@@ -4791,14 +4935,252 @@ export async function taskcreation( req, res ) {
4791
4935
  checkListName: data.checkListName,
4792
4936
  client_id: inputBody.clientId,
4793
4937
  userId: userId,
4794
- assignId: storeDetails._id,
4795
4938
  };
4796
4939
  await taskAssignService.create( userDetails );
4797
4940
  await insertSingleProcessData( response?._id );
4798
- return res.sendSuccess( 'Task created successfully' );
4941
+ return res.sendSuccess( { sourceCheckList_id: response?._id } );
4799
4942
  }
4800
4943
  } catch ( e ) {
4801
4944
  logger.error( { function: 'taskcreation ventota', error: e } );
4802
4945
  return res.sendError( e, 500 );
4803
4946
  }
4804
4947
  }
4948
+ export async function breachedTasks( req, res ) {
4949
+ try {
4950
+ let inputBody = req.body;
4951
+
4952
+
4953
+ inputBody.taskDescription = '';
4954
+ let userId;
4955
+ let storeDetails = await storeService.findOne( { storeId: inputBody.storeId, clientId: inputBody.clientId, status: 'active' }, { storeId: 1, storeName: 1, storeProfile: 1 } );
4956
+ if ( !storeDetails ) {
4957
+ return res.sendError( 'Store Not Found', 500 );
4958
+ }
4959
+
4960
+ let url = JSON.parse( process.env.LAMBDAURL );
4961
+ let checklistId = url.dailystoreChecklistId;
4962
+ let finduser = await checklistassignconfigModel.findOne( { checkListId: new mongoose.Types.ObjectId( checklistId ), store_id: storeDetails.storeId } );
4963
+
4964
+ if ( !finduser ) {
4965
+ return res.sendError( 'No user Found For this store', 500 );
4966
+ }
4967
+
4968
+ userId = finduser.userId;
4969
+ inputBody.userName = finduser.userName;
4970
+ inputBody.userEmail = finduser.userEmail;
4971
+
4972
+
4973
+ let teamList = await findteams( { users: { $elemMatch: { email: finduser.userEmail } } } );
4974
+
4975
+ inputBody.approver = '';
4976
+ for ( let team of teamList ) {
4977
+ for ( let user of team.Teamlead ) {
4978
+ inputBody.approver = user.email + ',' + inputBody.approver;
4979
+ }
4980
+ }
4981
+ inputBody.approver = inputBody.approver.replace( /,$/, '' );
4982
+
4983
+
4984
+ let title = `New Task Alert ${inputBody.taskName}-${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}`;
4985
+ let time = inputBody?.scheduleEndTime || '11:59 PM';
4986
+ let date = inputBody?.scheduleDate || dayjs().format( 'YYYY-MM-DD' );
4987
+ let description = `A new task has been assigned to ${storeDetails.storeName}. Please complete it before the due date of ${date}.`;
4988
+ if ( userDetails&&userDetails.fcmToken ) {
4989
+ const fcmToken = userDetails.fcmToken;
4990
+ await sendPushNotification( title, description, fcmToken );
4991
+ }
4992
+ const inputDateTime = dayjs.utc( `${date} ${time}`, 'YYYY-MM-DD hh:mm A' );
4993
+ const currentTime = dayjs.utc();
4994
+ if ( inputDateTime.isBefore( currentTime ) ) {
4995
+ return res.sendError( 'The input date-time is before the current time.', 500 );
4996
+ }
4997
+
4998
+ let approverList = inputBody?.approver.split( ',' );
4999
+
5000
+
5001
+ let userAdmin = await userService.find( { clientId: inputBody.clientId, email: { $in: approverList }, userType: 'client', isActive: true }, { name: '$userName', email: 1 } );
5002
+
5003
+ if ( userAdmin && userAdmin.length === 0 ) {
5004
+ userAdmin = await userService.find( { clientId: inputBody.clientId, email: 'rohit.chawla@lenskart.com', userType: 'client', isActive: true }, { name: '$userName', email: 1 } );
5005
+ }
5006
+
5007
+ let creator = await userService.find( { clientId: inputBody.clientId, email: 'rohit.chawla@lenskart.com', userType: 'client', isActive: true } );
5008
+ if ( creator && creator.length === 0 ) {
5009
+ return res.sendError( 'Invalid Creator Details', 500 );
5010
+ }
5011
+
5012
+ if ( req.body && req.body.referenceImage && req.body.referenceImage.length > 3 ) {
5013
+ return res.sendError( 'Maximum 3 referenceImage only allowed', 500 );
5014
+ }
5015
+ let data = {
5016
+ checkListName: `${inputBody.taskName}(${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )})`,
5017
+ checkListDescription: inputBody.taskDescription,
5018
+ createdBy: creator[0]._id,
5019
+ createdByName: creator[0].userName,
5020
+ publish: true,
5021
+ questionCount: 1,
5022
+ storeCount: 1,
5023
+ scheduleDate: date,
5024
+ scheduleEndTime: time,
5025
+ scheduleEndTimeISO: dayjs.utc( `${date} ${time}`, 'YYYY-MM-DD hh:mm A' ).format(),
5026
+ priorityType: 'high',
5027
+ client_id: inputBody.clientId,
5028
+ checkListType: 'task',
5029
+ publishDate: new Date(),
5030
+ locationCount: 1,
5031
+ ...( inputBody?.checkListId ) ? { referenceCheckListId: inputBody?.checkListId } : {},
5032
+ };
5033
+ data['approver'] = userAdmin;
5034
+ let answer = await findAnswer( inputBody?.answerType );
5035
+ if ( answer.length == 0 ) {
5036
+ return res.sendError( 'please enter Valid AnswerType', 500 );
5037
+ }
5038
+ if ( inputBody?.answerType === 'multiplechoicesingle' || inputBody?.answerType === 'multiplechoicemultiple' ) {
5039
+ if ( inputBody?.options && inputBody?.options.length > 0 ) {
5040
+ let optionsResult = [];
5041
+ let optionList = inputBody?.options.split( ',' );
5042
+ for ( let option of optionList ) {
5043
+ let optiondata = {
5044
+ 'answer': '',
5045
+ 'sopFlag': false,
5046
+ 'validation': false,
5047
+ 'validationType': '',
5048
+ 'referenceImage': [],
5049
+ 'runAI': false,
5050
+ 'allowUploadfromGallery': false,
5051
+ 'descriptivetype': '',
5052
+ 'showLinked': false,
5053
+ 'linkedQuestion': 0,
5054
+ 'nestedQuestion': [],
5055
+ };
5056
+ optiondata.answer = option;
5057
+ optionsResult.push( optiondata );
5058
+ }
5059
+ answer = optionsResult;
5060
+ } else {
5061
+ return res.sendError( 'please enter Valid Options', 500 );
5062
+ }
5063
+ }
5064
+ let response = await taskService.create( data );
5065
+ if ( response?.approver.length ) {
5066
+ let inputData = [];
5067
+ response?.approver.forEach( ( ele ) => {
5068
+ inputData.push( {
5069
+ userEmail: ele.email,
5070
+ checkListId: response._id,
5071
+ type: 'task',
5072
+ client_id: inputBody.clientId,
5073
+ checkListName: data?.checkListName || '',
5074
+ } );
5075
+ } );
5076
+ await traxApprover.insertMany( inputData );
5077
+ }
5078
+ if ( response?._id ) {
5079
+ let question = [];
5080
+ for ( let [ index, ques ] of inputBody.questions.entries() ) {
5081
+ let answer = await findAnswer( ques?.answerType );
5082
+ if ( answer.length == 0 ) {
5083
+ return res.sendError( 'please enter Valid AnswerType', 500 );
5084
+ }
5085
+ if ( ques?.answerType === 'multiplechoicesingle' || ques?.answerType === 'multiplechoicemultiple' ) {
5086
+ if ( ques?.options && ques?.options.length > 1 ) {
5087
+ let optionsResult = [];
5088
+ for ( let option of ques?.options ) {
5089
+ let optiondata = {
5090
+ 'answer': '',
5091
+ 'sopFlag': false,
5092
+ 'validation': false,
5093
+ 'validationType': '',
5094
+ 'referenceImage': [],
5095
+ 'runAI': false,
5096
+ 'allowUploadfromGallery': false,
5097
+ 'descriptivetype': '',
5098
+ 'showLinked': false,
5099
+ 'linkedQuestion': 0,
5100
+ 'nestedQuestion': [],
5101
+ };
5102
+ optiondata.answer = String( option );
5103
+ optionsResult.push( optiondata );
5104
+ }
5105
+ answer = optionsResult;
5106
+ } else {
5107
+ return res.sendError( 'please enter Valid Options', 500 );
5108
+ }
5109
+ }
5110
+ question.push( {
5111
+ 'qno': index+1,
5112
+ 'qname': ques.question,
5113
+ 'answerType': ques?.answerType || 'yes/no',
5114
+ 'runAI': false,
5115
+ 'runAIDescription': '',
5116
+ 'allowUploadfromGallery': false,
5117
+ 'linkType': false,
5118
+ 'questionReferenceImage': [],
5119
+ 'answers': answer,
5120
+ 'descriptivetype': 'text',
5121
+ } );
5122
+ let images = [];
5123
+ for ( let imgpath of req.body.referenceImage ) {
5124
+ let configURL = JSON.parse( process.env.BUCKET );
5125
+ let inputData = {
5126
+ Bucket: configURL.commonAiTaskBucket,
5127
+ Key: imgpath,
5128
+ };
5129
+ let output = await getObject( inputData );
5130
+ let image = {
5131
+ data: output.Body,
5132
+ name: imgpath,
5133
+ mimetype: output.ContentType,
5134
+ };
5135
+ let uplaodedImage = await uploadmultiImage( image );
5136
+
5137
+ let imgUrl = decodeURIComponent( uplaodedImage.imgUrl.split( '?' )[0] );
5138
+ let url = imgUrl.split( '/' );
5139
+ if ( url.includes( 'https:' ) || url.includes( 'http:' ) ) {
5140
+ url.splice( 0, 3 );
5141
+ }
5142
+ images.push( url.join( '/' ) );
5143
+ }
5144
+ question[0].questionReferenceImage = images;
5145
+
5146
+ if ( inputBody?.answerType === 'image' || inputBody?.answerType === 'descriptiveImage' || inputBody?.answerType === 'multipleImage' ) {
5147
+ answer[0].referenceImage = question[0].questionReferenceImage;
5148
+ }
5149
+
5150
+ // if ( inputBody?.answerType === 'image' || inputBody?.answerType === 'descriptiveImage' || inputBody?.answerType === 'multipleImage' ) {
5151
+ // answer[0].referenceImage = question[0].questionReferenceImage;
5152
+ // }
5153
+
5154
+ question = {
5155
+ checkListId: response?._id,
5156
+ question: question,
5157
+ section: 'Section 1',
5158
+ checkList: data.checkListName,
5159
+ client_id: inputBody.clientId,
5160
+ };
5161
+ await taskQuestionService.create( question );
5162
+
5163
+ let userDetails = {
5164
+ userName: inputBody.userName,
5165
+ userEmail: inputBody.userEmail,
5166
+ store_id: storeDetails.storeId,
5167
+ storeName: storeDetails.storeName,
5168
+ city: storeDetails?.storeProfile?.city,
5169
+ checkFlag: true,
5170
+ checkListId: response?._id,
5171
+ checkListName: data.checkListName,
5172
+ client_id: inputBody.clientId,
5173
+ userId: userId,
5174
+ assignId: storeDetails._id,
5175
+ };
5176
+ await taskAssignService.create( userDetails );
5177
+ await insertSingleProcessData( response?._id );
5178
+ return res.sendSuccess( 'Task created successfully' );
5179
+ }
5180
+ }
5181
+ } catch ( e ) {
5182
+ logger.error( { function: 'taskcreation Ai checklist breach', error: e } );
5183
+ return res.sendError( e, 500 );
5184
+ }
5185
+ }
5186
+
@@ -1,6 +1,6 @@
1
1
  import * as taskService from '../service/task.service.js';
2
2
  import * as processedTaskService from '../service/processedTaskList.service.js';
3
- import { logger, download } from 'tango-app-api-middleware'; // getChecklistUsers
3
+ import { logger, download, insertOpenSearchData } from 'tango-app-api-middleware'; // getChecklistUsers
4
4
  import dayjs from 'dayjs';
5
5
  import mongoose from 'mongoose';
6
6
  // const ObjectId = mongoose.Types.ObjectId;
@@ -961,7 +961,7 @@ export const taskDeleteV1 = async ( req, res ) => {
961
961
  return res.sendError( 'Missing taskId in request body', 400 );
962
962
  }
963
963
 
964
- const taskConfig = await taskService.findOne( { _id: new mongoose.Types.ObjectId( requestData.taskId ) }, { _id: 1 } );
964
+ const taskConfig = await taskService.findOne( { _id: new mongoose.Types.ObjectId( requestData.taskId ) } );
965
965
  if ( !taskConfig ) {
966
966
  // console.log( 'Task found:', taskConfig );
967
967
  return res.sendError( 'Task not found', 404 );
@@ -973,12 +973,29 @@ export const taskDeleteV1 = async ( req, res ) => {
973
973
  );
974
974
 
975
975
  if ( resultData ) {
976
+ let logObj = {
977
+ client_id: taskConfig.client_id,
978
+ createAt: new Date(),
979
+ sourceCheckList_id: taskConfig._id,
980
+ checkListName: taskConfig.checkListName,
981
+ fromCheckListName: '',
982
+ type: 'task',
983
+ action: 'deleted',
984
+ storeName: '',
985
+ store_id: '',
986
+ createdByEmail: req.user.email,
987
+ createdBy: req.user.userName,
988
+ coverage: taskConfig.coverage,
989
+ logDetails: {},
990
+ };
991
+ insertOpenSearchData( JSON.parse( process.env.OPENSEARCH ).traxActivityLog, logObj );
976
992
  // console.log( 'Update result:', resultData );
977
993
  return res.sendSuccess( { message: 'Task deleted successfully' } );
978
994
  } else {
979
995
  return res.sendError( 'Something went wrong please try again', 500 );
980
996
  }
981
997
  } catch ( e ) {
998
+ // console.log( 'e', e );
982
999
  logger.error( 'taskDeleteV1 =>', e );
983
1000
  return res.sendError( e, 500 );
984
1001
  }
@@ -21,7 +21,7 @@ export const StoreHygienetaskSchema = Joi.object().keys( {
21
21
  scheduleDate: Joi.string().optional(),
22
22
  scheduleEndTime: Joi.string().optional(),
23
23
  referenceImage: Joi.array().required(),
24
- count: Joi.number().required(),
24
+ zoneName: Joi.string().required(),
25
25
  } );
26
26
 
27
27
 
@@ -38,6 +38,7 @@ taskRouter
38
38
  .post( '/commonAiTask', isAllowedInternalAPIHandler, validate( commonAiTaskvalidation ), taskController.commonAiTask )
39
39
  .post( '/updateAssign', isAllowedSessionHandler, taskController.updateAssign )
40
40
  .post( '/taskcreation', isAllowedInternalAPIHandler, validate( taskcreationvalidation ), taskController.taskcreation )
41
+ .post( '/breached-tasks', isAllowedInternalAPIHandler, validate( taskcreationvalidation ), taskController.breachedTasks )
41
42
  .get( '/getcoustemer', taskController.customertrial );
42
43
 
43
44