tango-app-api-task 3.2.1-beta-41 → 3.2.1-hotfix-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.
@@ -8,9 +8,7 @@ import * as storeService from '../service/store.service.js';
8
8
  import * as traxApprover from '../service/approver.service.js';
9
9
  import * as processedChecklist from '../service/processedChecklist.service.js';
10
10
  import * as checklistassignconfigModel from '../service/checklistAssign.service.js';
11
- import * as clusterServices from '../service/cluster.service.js';
12
- import * as teamsServices from '../service/teams.service.js';
13
- // import * as clusterModel from '../service/cluster.service.js';
11
+ import * as clusterModel from '../service/cluster.service.js';
14
12
  // import * as domainService from '../service/domain.service.js';
15
13
  import mongoose from 'mongoose';
16
14
  const ObjectId = mongoose.Types.ObjectId;
@@ -127,6 +125,38 @@ export async function createUpdateTask( req, res ) {
127
125
  } );
128
126
  } );
129
127
 
128
+ for ( let [ index, question ] of section.questions.entries() ) {
129
+ await processNested( index, question );
130
+ }
131
+
132
+ async function processNested( qIdx, question, nestedIndex = -1 ) {
133
+ if ( question?.answers?.length ) {
134
+ for ( let [ index, answer ] of question?.answers?.entries() ) {
135
+ if ( !section.questions[qIdx].answers[index]?.nestedQuestion && nestedIndex == -1 ) {
136
+ section.questions[qIdx].answers[index].nestedQuestion = [];
137
+ }
138
+ if ( answer.showLinked ) {
139
+ if ( nestedIndex != -1 ) {
140
+ section.questions[qIdx].answers[nestedIndex].nestedQuestion.push( answer.linkedQuestion );
141
+ } else {
142
+ section.questions[qIdx].answers[index].nestedQuestion.push( answer.linkedQuestion );
143
+ }
144
+ let nestedLinkedQuestion = section.questions.find( ( item ) => item.qno == answer.linkedQuestion );
145
+ if ( nestedLinkedQuestion ) {
146
+ let findNestedAnswers = nestedLinkedQuestion.answers.find( ( item ) => item.showLinked );
147
+ if ( findNestedAnswers ) {
148
+ if ( nestedIndex != -1 ) {
149
+ await processNested( qIdx, nestedLinkedQuestion, nestedIndex );
150
+ } else {
151
+ await processNested( qIdx, nestedLinkedQuestion, index );
152
+ }
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+
130
160
  sectionList.push( {
131
161
  section: section?.name || 'Section 1',
132
162
  createdBy: req.user._id,
@@ -264,29 +294,9 @@ export async function taskDetails( req, res ) {
264
294
  }
265
295
  if ( storechecklistdetails ) {
266
296
  result.checkListDetails = { ...storechecklistdetails._doc };
267
- let query = {
268
- checkListId: storechecklistdetails._id,
269
- ...( storechecklistdetails.coverage == 'store' ) ? { $or: [ { store_id: { $exists: true } }, { clusterName: { $exists: true } } ] } : { $or: [ { userEmail: { $exists: true } }, { teamName: { $exists: true } } ] },
270
- };
271
- let assignList = await taskAssignService.find( query, { _id: 1, store_id: 1, clusterName: 1, userEmail: 1, teamName: 1, assignId: 1 } );
272
- let singleAssign;
273
- let groupAssign;
274
- if ( storechecklistdetails.coverage == 'store' ) {
275
- singleAssign = assignList.filter( ( item ) => typeof item?.store_id != 'undefined' && item?.store_id != '' ).map( ( item ) => {
276
- return { id: item.assignId, type: 'store' };
277
- } );
278
- groupAssign = assignList.filter( ( item ) => typeof item?.clusterName != 'undefined' && item?.clusterName != '' ).map( ( item ) => {
279
- return { id: item.assignId, type: 'cluster' };
280
- } );
281
- } else {
282
- singleAssign = assignList.filter( ( item ) => typeof item?.userEmail != 'undefined' && item?.userEmail !='' ).map( ( item ) => {
283
- return { id: item.assignId, type: 'user' };
284
- } );
285
- groupAssign = assignList.filter( ( item ) => typeof item?.teamName != 'undefined' && item?.teamName != '' ).map( ( item ) => {
286
- return { id: item.assignId, type: 'teams' };
287
- } );
288
- }
289
- result.checkListDetails = { ...result.checkListDetails, ...{ sections: sectionList }, singleAssign, groupAssign };
297
+ let removedUsers = await taskAssignService.find( { checkFlag: false, checkListId: storechecklistdetails._id }, { _id: 1 } );
298
+ removedUsers = removedUsers?.map( ( item ) => item._id );
299
+ result.checkListDetails = { ...result.checkListDetails, ...{ sections: sectionList }, ...{ removedUsers: removedUsers } };
290
300
  }
291
301
  return res.sendSuccess( result );
292
302
  } catch ( e ) {
@@ -455,189 +465,6 @@ export async function validateUser( req, res ) {
455
465
  }
456
466
  };
457
467
 
458
- export const validateUserv1 = async ( req, res ) => {
459
- try {
460
- if ( !req.body.assignedUsers.length ) {
461
- return res.sendError( 'Please Enter user Details', 400 );
462
- }
463
-
464
- let assignDetails = req.body.assignedUsers;
465
-
466
- if ( req.body.coverage == 'store' ) {
467
- const duplicateStore = assignDetails.reduce( ( acc, obj ) => {
468
- if ( !acc[obj.storeName.toLowerCase()] ) {
469
- acc[obj.storeName.toLowerCase()] = {
470
- email: [ obj.userEmail.toLowerCase() ],
471
- count: 1,
472
- };
473
- } else {
474
- if ( acc[obj.storeName.toLowerCase()] ) {
475
- if ( acc[obj.storeName.toLowerCase()].email.includes( obj.userEmail.toLowerCase() ) ) {
476
- acc[obj.storeName.toLowerCase()].count++;
477
- } else {
478
- acc[obj.storeName.toLowerCase()].email.push( obj.userEmail.toLowerCase() );
479
- }
480
- }
481
- }
482
- return acc;
483
- }, {} );
484
-
485
- const duplicateStores = Object.keys( duplicateStore ).filter( ( storeName ) => duplicateStore[storeName].count > 1 );
486
- if ( duplicateStores.length ) {
487
- return res.sendError( { validate: false, duplicates: duplicateStores, message: 'Store and email is duplicated' }, 400 );
488
- }
489
- } else {
490
- const duplicateUser = assignDetails.reduce( ( acc, obj ) => {
491
- if ( !acc[obj.userEmail.toLowerCase()] ) {
492
- acc[obj.userEmail.toLowerCase()] = {
493
- name: [ obj.userName.toLowerCase() ],
494
- count: 1,
495
- };
496
- } else {
497
- if ( acc[obj.userEmail.toLowerCase()] ) {
498
- if ( acc[obj.userEmail.toLowerCase()].name.includes( obj.userName.toLowerCase() ) ) {
499
- acc[obj.userEmail.toLowerCase()].count++;
500
- } else {
501
- acc[obj.userEmail.toLowerCase()].name.push( obj.userEmail.toLowerCase() );
502
- }
503
- }
504
- }
505
- return acc;
506
- }, {} );
507
-
508
- const duplicateUsers = Object.keys( duplicateUser ).filter( ( storeName ) => duplicateUser[storeName].count > 1 );
509
- if ( duplicateUsers.length ) {
510
- return res.sendError( { validate: false, duplicates: duplicateUsers, message: 'Email is Duplicated' }, 400 );
511
- }
512
- }
513
-
514
- if ( req.body.hasOwnProperty( 'addSingle' ) ) {
515
- let checkExists = await taskAssignService.findOne( { userEmail: assignDetails[0]?.userEmail, storeName: assignDetails[0]?.storeName, checkListId: req.body.id } );
516
- if ( checkExists ) {
517
- return res.sendError( 'User already Exists', 400 );
518
- }
519
- }
520
-
521
- let userEmailList = assignDetails.map( ( item ) => item.userEmail?.trim()?.toLowerCase() );
522
- let storeList = assignDetails.map( ( item ) => item?.storeName?.trim()?.toLowerCase() );
523
-
524
- let userQuery = [
525
- {
526
- $project: {
527
- newEmail: { $toLower: '$email' },
528
- isActive: 1,
529
- clientId: 1,
530
- userName: 1,
531
- email: 1,
532
- },
533
- },
534
- {
535
- $match: {
536
- newEmail: { $in: userEmailList },
537
- isActive: true,
538
- clientId: req.body.clientId,
539
- },
540
- },
541
- ];
542
-
543
- let emailCheckQuery = [
544
- {
545
- $project: {
546
- newEmail: { $toLower: '$email' },
547
- isActive: 1,
548
- clientId: 1,
549
- },
550
- },
551
- {
552
- $match: {
553
- newEmail: { $in: userEmailList },
554
- isActive: true,
555
- clientId: { $ne: req.body.clientId },
556
- },
557
- },
558
- ];
559
-
560
- let storeQuery = [
561
- {
562
- $project: {
563
- 'store': { $toLower: '$storeName' },
564
- 'clientId': 1,
565
- 'storeProfile.city': 1,
566
- 'status': 1,
567
- 'storeId': 1,
568
- 'spocDetails': 1,
569
- 'storeName': 1,
570
- },
571
- },
572
- {
573
- $match: {
574
- clientId: req.body.clientId,
575
- store: { $in: storeList },
576
- },
577
- },
578
- ];
579
-
580
- let [ userDetails, storeDetails, existEmail ] = await Promise.all( [
581
- await userService.aggregate( userQuery ),
582
- await storeService.aggregate( storeQuery ),
583
- await userService.aggregate( emailCheckQuery ),
584
- ] );
585
-
586
- existEmail = existEmail.map( ( ele ) => ele.newEmail );
587
- let existUserEmail = userDetails.map( ( ele ) => ele.newEmail );
588
- let newUserList = userEmailList.filter( ( ele ) => !existUserEmail.includes( ele ) && !existEmail.includes( ele ) );
589
- let inActiveStores = storeDetails.filter( ( ele ) => ele.status == 'deactive' ).map( ( ele ) => ele.storeName );
590
-
591
- let existsStore = storeDetails.map( ( ele ) => ele.storeName.toLowerCase() );
592
- let newStoreList = storeList.filter( ( ele ) => ele != null && !existsStore.includes( ele.toLowerCase() ) );
593
- if ( req.body.coverage == 'store' ) {
594
- assignDetails.forEach( ( item ) => {
595
- let getStoreDetails = storeDetails.find( ( store ) => store.storeName.toLowerCase() == item.storeName.toLowerCase() );
596
- if ( getStoreDetails ) {
597
- let storeUserDetails = userDetails.find( ( ele ) => ele.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
598
- item._id = getStoreDetails._id;
599
- item.storeId = getStoreDetails.storeId;
600
- item.userName = getStoreDetails?.spocDetails?.[0]?.email.toLowerCase() == item.userEmail.toLowerCase() ? getStoreDetails?.spocDetails?.[0]?.name : storeUserDetails?.email == item.userEmail.toLowerCase() ? storeUserDetails?.userName : item.userName;
601
- item.storeName = getStoreDetails.storeName;
602
- item.userEmail = storeUserDetails?.email || item.userEmail;
603
- }
604
- } );
605
- } else {
606
- assignDetails.forEach( ( item ) => {
607
- let getUserDetails = userDetails.find( ( user ) => user.newEmail.toLowerCase() == item.userEmail.toLowerCase() );
608
- if ( getUserDetails ) {
609
- item._id = getUserDetails._id;
610
- item.userName = getUserDetails.userName;
611
- item.userEmail = getUserDetails.email;
612
- }
613
- } );
614
- }
615
-
616
- if ( ( newUserList.length || newStoreList.length || existEmail.length || inActiveStores.length ) && !req.body?.addUser ) {
617
- return res.sendError( { validate: false, user: newUserList, store: newStoreList, existEmail, inActiveStores, data: assignDetails }, 400 );
618
- }
619
- await Promise.all( newUserList.map( async ( ele ) => {
620
- let findUserIndex = assignDetails.findIndex( ( item ) => item?.userEmail?.toLowerCase() == ele?.toLowerCase() );
621
- if ( findUserIndex != -1 ) {
622
- let data = {
623
- userName: assignDetails[findUserIndex]?.userName,
624
- email: ele,
625
- mobileNumber: assignDetails[findUserIndex]?.mobileNumber,
626
- clientId: req.body.clientId,
627
- };
628
- let response = await createUser( data );
629
- if ( req.body.coverage == 'user' ) {
630
- assignDetails[findUserIndex]._id = response._id;
631
- }
632
- }
633
- } ) );
634
- return res.sendSuccess( { validate: true, data: assignDetails } );
635
- } catch ( e ) {
636
- logger.error( 'validateUser 2=>', e );
637
- return res.sendError( e, 500 );
638
- }
639
- };
640
-
641
468
  async function uploadUser( req, res ) {
642
469
  try {
643
470
  let inputBody = req.body;
@@ -768,76 +595,55 @@ export async function userDetails( req, res ) {
768
595
  if ( !req.query.taskId ) {
769
596
  return res.sendError( { message: 'Task Id is required' }, 400 );
770
597
  }
771
- // let limit = parseInt( req.query.limit ) || 5;
772
- // let page = parseInt( req.query.offset ) || 0;
773
- // let skip = limit * page;
598
+ let limit = parseInt( req.query.limit ) || 5;
599
+ let page = parseInt( req.query.offset ) || 0;
600
+ let skip = limit * page;
601
+
602
+ let query = [ { $match: { checkListId: new ObjectId( req.query.taskId ) } } ];
603
+ if ( req.query?.search?.trim() && req.query?.search?.trim() != '' ) {
604
+ let searchValue = req.query.search;
605
+ searchValue = searchValue.split( ',' ).map( ( item ) => item.trim().toLowerCase() );
606
+ if ( searchValue.length > 1 ) {
607
+ query.push( { $addFields: { storeLower: { $toLower: '$storeName' } } } );
608
+ query.push( { $match: { storeLower: { $in: searchValue } } } );
609
+ } else {
610
+ query.push( { $match: { storeName: { $regex: req.query.search.trim(), $options: 'i' } } } );
611
+ }
612
+ }
774
613
 
775
- let query = [ { $match: { checkListId: new ObjectId( req.query.taskId ), isdeleted: false } }, { $sort: { _id: -1 } } ];
614
+ query.push( {
615
+ $facet: {
616
+ data: [
617
+ { $skip: skip }, { $limit: limit },
618
+ ],
619
+ count: [
620
+ { $count: 'total' },
621
+ ],
622
+ },
623
+ } );
776
624
 
777
625
  let taskDetails = await taskAssignService.aggregate( query );
778
- if ( !taskDetails.length ) {
626
+
627
+ if ( !taskDetails[0].data.length ) {
779
628
  return res.sendError( 'No data found', 204 );
780
629
  }
781
630
 
782
631
  let userDetails = [];
783
- await Promise.all( taskDetails.map( async ( ele ) => {
784
- if ( ele?.clusterName ) {
785
- let clusterDetails = await clusterServices.findOneCluster( { _id: ele.assignId }, { stores: 1 } );
786
- if ( clusterDetails ) {
787
- let storeDetails = await storeService.find( { _id: { $in: clusterDetails.stores.map( ( item ) => item.store ) }, status: 'active' } );
788
- storeDetails.forEach( ( item ) => {
789
- userDetails.push( {
790
- id: ele.assignId,
791
- userName: item.spocDetails?.[0]?.name,
792
- userEmail: item.spocDetails?.[0]?.email,
793
- storeId: item?.storeId,
794
- storeName: item?.storeName,
795
- userPhone: item.spocDetails?.[0]?.phone,
796
- city: ele?.city,
797
- checkFlag: ele.checkFlag,
798
- clusterName: ele?.clusterName || '',
799
- teamName: ele?.teamName || '',
800
- } );
801
- } );
802
- }
803
- } else if ( ele?.teamName ) {
804
- let teamDetails = await teamsServices.findOneTeams( { _id: ele.assignId }, { users: 1, teamName: 1 } );
805
- if ( teamDetails ) {
806
- let teamUserDetails = await userService.find( { _id: { $in: teamDetails.users.map( ( item ) => item.userId ) } } );
807
- teamUserDetails.forEach( ( item ) => {
808
- userDetails.push( {
809
- id: ele.assignId,
810
- userName: item.userName,
811
- userEmail: item.email,
812
- storeId: ele?.storeId,
813
- storeName: ele?.storeName,
814
- userPhone: item?.mobileNumber,
815
- city: ele?.city,
816
- checkFlag: ele.checkFlag,
817
- clusterName: ele?.clusterName || '',
818
- teamName: ele?.teamName || '',
819
- } );
820
- } );
821
- }
822
- } else {
823
- userDetails.push( {
824
- _id: ele.assignId,
825
- userName: ele.userName,
826
- userEmail: ele.userEmail,
827
- storeId: ele?.store_id,
828
- storeName: ele?.storeName,
829
- userPhone: ele.userPhone,
830
- city: ele.city,
831
- checkFlag: ele.checkFlag,
832
- clusterName: ele?.clusterName || '',
833
- teamName: ele?.teamName || '',
834
- } );
835
- }
836
- } ) );
837
-
838
- return res.sendSuccess( { count: userDetails.length, userDetails } );
632
+ taskDetails[0].data.forEach( ( item ) => {
633
+ userDetails.push( {
634
+ id: item._id,
635
+ userName: item.userName,
636
+ userEmail: item.userEmail,
637
+ store_id: item.store_id,
638
+ storeName: item.storeName,
639
+ userPhone: item.userPhone,
640
+ city: item.city,
641
+ checkFlag: item.checkFlag,
642
+ } );
643
+ } );
644
+ return res.sendSuccess( { users: userDetails, count: taskDetails[0].count[0].total } );
839
645
  } catch ( e ) {
840
- logger.error( 'userDetails =>', e );
646
+ logger.error( { functionName: 'userDetails', error: e, message: req.body } );
841
647
  return res.sendError( e, 500 );
842
648
  }
843
649
  };
@@ -845,22 +651,20 @@ export async function userDetails( req, res ) {
845
651
  export async function taskConfig( req, res ) {
846
652
  try {
847
653
  let inputBody = req.body;
654
+ let storeCount = 0;
655
+ let locationCount = 0;
848
656
  let checklistDetails;
849
657
  inputBody.client_id = inputBody.clientId;
850
658
  if ( !inputBody._id ) {
851
659
  return res.sendError( { message: 'Task Id is Required' }, 400 );
852
660
  }
853
661
 
854
- if ( !inputBody.assignedUsers.length && inputBody.submitType == 'publish' ) {
855
- return res.sendError( 'Please Assigned a user', 400 );
662
+ if ( inputBody.submitType == 'publish' ) {
663
+ let checkUserAssigned = await taskAssignService.findOne( { checkListId: inputBody._id, checkFlag: true } );
664
+ if ( !checkUserAssigned ) {
665
+ return res.sendError( { message: 'Please assign a user' }, 400 );
666
+ }
856
667
  }
857
-
858
- // if ( inputBody.submitType == 'publish' ) {
859
- // let checkUserAssigned = await taskAssignService.findOne( { checkListId: inputBody._id, checkFlag: true } );
860
- // if ( !checkUserAssigned ) {
861
- // return res.sendError( { message: 'Please assign a user' }, 400 );
862
- // }
863
- // }
864
668
  if ( !inputBody?.approver.length && inputBody.submitType == 'publish' ) {
865
669
  return res.sendError( { message: 'Please assign approver' }, 400 );
866
670
  }
@@ -878,7 +682,7 @@ export async function taskConfig( req, res ) {
878
682
  };
879
683
  await checklistLogs.create( logInsertData );
880
684
 
881
- checklistDetails = await taskService.findOne( { _id: inputBody._id, isdeleted: false, client_id: inputBody.clientId } );
685
+ checklistDetails = await taskService.findOne( { _id: inputBody._id, isdeleted: false } );
882
686
 
883
687
  if ( !checklistDetails ) {
884
688
  return res.sendError( 'No data found', 204 );
@@ -916,7 +720,39 @@ export async function taskConfig( req, res ) {
916
720
  await traxApprover.insertMany( data );
917
721
  }
918
722
  }
723
+ await taskAssignService.updateMany( { checkListId: inputBody._id }, { checkFlag: true } );
724
+ if ( inputBody.removedUsers.length ) {
725
+ await taskAssignService.updateMany( { _id: { $in: inputBody.removedUsers } }, { checkFlag: false } );
726
+ }
919
727
  let storeConfigDetails = await taskAssignService.find( { checkListId: inputBody._id, checkFlag: true }, { _id: 0, store_id: 1, userEmail: 1, storeName: 1 } );
728
+ let storeList = storeConfigDetails.map( ( store ) => store.store_id );
729
+
730
+ storeCount = storeList.length;
731
+ if ( storeList.length ) {
732
+ let query = [
733
+ {
734
+ $match: {
735
+ client_id: inputBody.client_id,
736
+ id: { $in: storeList },
737
+ city: { $exists: true },
738
+ },
739
+ },
740
+ {
741
+ $group: {
742
+ _id: '$city',
743
+ },
744
+ },
745
+ {
746
+ $project: {
747
+ _id: 0,
748
+ city: '$_id',
749
+ },
750
+ },
751
+ ];
752
+ let storeDetails = await storeService.aggregate( query );
753
+ locationCount = storeDetails.length;
754
+ }
755
+ await taskService.updateOne( { _id: inputBody._id }, { storeCount, locationCount } );
920
756
  if ( inputBody.submitType == 'publish' ) {
921
757
  let taskName = checklistDetails.checkListName;
922
758
  let dueDate = dayjs( configDetails.scheduleEndTimeISO ).format( 'YYYY-MM-DD hh:mm A' );
@@ -1009,7 +845,6 @@ export async function insertSingleProcessData( checklistId ) {
1009
845
  insertdata.remainder = getCLconfig?.remainder || [];
1010
846
  insertdata.approver = getCLconfig?.approver || [];
1011
847
  insertdata.restrictAttendance = getCLconfig?.restrictAttendance;
1012
- insertdata.coverage = getCLconfig?.coverage;
1013
848
  let collectSections = [];
1014
849
  let sectionQuery = [];
1015
850
  sectionQuery.push( {
@@ -1075,6 +910,7 @@ export async function insertSingleProcessData( checklistId ) {
1075
910
  await taskProcessedConfigService.updateOne( { _id: checklistDetails._id }, insertDataPerDay );
1076
911
  updatedchecklist = checklistDetails;
1077
912
  }
913
+
1078
914
  if ( updatedchecklist ) {
1079
915
  await insertPCBulkV3( getCLconfig, checklistId, updatedchecklist, dateVal, startTimeIso, endTimeIso, insertdata );
1080
916
  }
@@ -1090,13 +926,16 @@ export async function insertSingleProcessData( checklistId ) {
1090
926
 
1091
927
  async function insertPCBulkV3( getCLconfig, checklistId, updatedchecklist, date, startTimeIso, endTimeIso, insertdata ) {
1092
928
  let getquestionQuery = [];
929
+
1093
930
  if ( dayjs( getCLconfig.publishDate ).format( 'YYYY-MM-DD' ) != dayjs( date ).format( 'YYYY-MM-DD' ) ) {
1094
931
  let todayDate = `${dayjs( date ).format( 'YYYY-MM-DD' )} 00:00 AM`;
1095
932
  startTimeIso = dayjs.utc( todayDate, 'YYYY-MM-DD HH:mm A' );
1096
933
  }
934
+
1097
935
  getquestionQuery.push( {
1098
936
  $match: {
1099
937
  checkListId: new ObjectId( checklistId ),
938
+ checkFlag: true,
1100
939
  isdeleted: false,
1101
940
  },
1102
941
  } );
@@ -1105,109 +944,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, updatedchecklist, date,
1105
944
 
1106
945
  if ( allQuestion ) {
1107
946
  let userIdList = [];
1108
- let assignList = [];
1109
- let assignUserList = [];
1110
- if ( getCLconfig.coverage == 'store' ) {
1111
- let clusterList = allQuestion.filter( ( ele ) => ele?.clusterName ).map( ( item ) => item.assignId );
1112
- if ( clusterList.length ) {
1113
- let clusterDetails = await clusterServices.findcluster( { _id: { $in: clusterList } } );
1114
- if ( clusterDetails.length ) {
1115
- let idList = clusterDetails.flatMap( ( item ) => item.stores.map( ( ele ) => ele.store ) );
1116
- let getStoreDetails = await storeService.find( { _id: { $in: idList }, status: 'active' } );
1117
- if ( getStoreDetails.length ) {
1118
- getStoreDetails = getStoreDetails.filter( ( store ) => {
1119
- let findStore = allQuestion.find( ( storeList ) => storeList.assignId.toString() == store._id.toString() );
1120
- if ( findStore ) {
1121
- return store?.spocDetails?.[0]?.email.toLowerCase() != findStore.userEmail.toLowerCase();
1122
- } else {
1123
- return true;
1124
- }
1125
- } );
1126
- assignList = await Promise.all( getStoreDetails.map( async ( store ) => {
1127
- let userQuery = [
1128
- {
1129
- $project: {
1130
- newEmail: { $toLower: '$email' },
1131
- isActive: 1,
1132
- clientId: 1,
1133
- userName: 1,
1134
- email: 1,
1135
- },
1136
- },
1137
- {
1138
- $match: {
1139
- newEmail: store?.spocDetails?.[0]?.email.toLowerCase(),
1140
- isActive: true,
1141
- clientId: store.clientId,
1142
- },
1143
- },
1144
- ];
1145
- let userDetails = await userService.aggregate( userQuery );
1146
- if ( !userDetails.length ) {
1147
- let data = {
1148
- clientId: store.clientId,
1149
- userName: store.spocDetails?.[0]?.name,
1150
- mobileNumber: store.spocDetails?.[0]?.phone || '',
1151
- email: store.spocDetails[0].email,
1152
- };
1153
- userDetails = await createUser( data );
1154
- userDetails = [ userDetails ];
1155
- }
1156
- let data = {
1157
- store_id: store?.storeId,
1158
- storeName: store?.storeName,
1159
- userId: userDetails?.[0]?._id,
1160
- userName: userDetails?.[0]?.userName,
1161
- userEmail: userDetails?.[0]?.email,
1162
- userPhone: userDetails?.[0]?.mobileNumber,
1163
- city: store?.storeProfile?.city,
1164
- country: store?.storeProfile?.country,
1165
- checkFlag: true,
1166
- checkListId: getCLconfig._id,
1167
- checkListName: getCLconfig.checkListName,
1168
- client_id: getCLconfig.client_id,
1169
- };
1170
- return data;
1171
- } ) );
1172
- }
1173
- }
1174
- }
1175
- allQuestion = allQuestion.filter( ( ele ) => !clusterList.includes( ele.assignId ) );
1176
- }
1177
- if ( getCLconfig.coverage == 'user' ) {
1178
- let teamsList = allQuestion.filter( ( ele ) => ele?.teamName ).map( ( item ) => item.assignId );
1179
- if ( teamsList.length ) {
1180
- let teamDetails = await teamsServices.findteams( { _id: { $in: teamsList } } );
1181
- if ( teamDetails.length ) {
1182
- let idList = teamDetails.flatMap( ( item ) => item.users.map( ( ele ) => ele.userId ) );
1183
- let userIdList = allQuestion.filter( ( qn ) => !qn?.teamName ).map( ( qn ) => qn.assignId.toString() );
1184
- idList = idList.filter( ( id ) => !userIdList.includes( id.toString() ) );
1185
- let getUserDetails = await userService.find( { _id: { $in: idList } } );
1186
- if ( getUserDetails.length ) {
1187
- assignList = getUserDetails.map( ( user ) => {
1188
- let data = {
1189
- store_id: '',
1190
- storeName: '',
1191
- userId: user._id,
1192
- userName: user.userName,
1193
- userEmail: user.email,
1194
- userPhone: user?.mobileNumber,
1195
- city: '',
1196
- country: '',
1197
- checkFlag: true,
1198
- checkListId: getCLconfig._id,
1199
- checkListName: getCLconfig.checkListName,
1200
- client_id: getCLconfig.client_id,
1201
- };
1202
- return data;
1203
- } );
1204
- }
1205
- }
1206
- }
1207
- allQuestion = allQuestion.filter( ( ele ) => !teamsList.includes( ele.assignId ) );
1208
- }
1209
- allQuestion = [ ...allQuestion, ...assignList ];
1210
- await Promise.all( allQuestion.map( async ( element4 ) => {
947
+ for ( let element4 of allQuestion ) {
1211
948
  let query;
1212
949
  query = {
1213
950
  date_string: dayjs( date ).format( 'YYYY-MM-DD' ),
@@ -1223,45 +960,43 @@ async function insertPCBulkV3( getCLconfig, checklistId, updatedchecklist, date,
1223
960
  let getsubmitDetails = await taskProcessedService.find( query );
1224
961
  if ( getsubmitDetails.length ) {
1225
962
  userIdList.push( element4._id );
1226
- } else {
1227
- delete element4._id;
1228
- delete element4.checkFlag;
1229
- delete element4.isdeleted;
1230
- delete element4.createdAt;
1231
- delete element4.updatedAt;
1232
- element4.checkListId = updatedchecklist._id;
1233
- element4.checkListName = getCLconfig.checkListName;
1234
- element4.checkListDescription = getCLconfig.checkListDescription;
1235
- element4.date_iso = new Date( dayjs( date, 'YYYY-MM-DD' ).format( 'YYYY-MM-DD' ) );
1236
- element4.date_string = dayjs( date ).format( 'YYYY-MM-DD' );
1237
- element4.allowedOverTime = false;
1238
- element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
1239
- element4.scheduleStartTime = '12:00 AM';
1240
- element4.scheduleStartTime_iso = startTimeIso.format();
1241
- element4.scheduleEndTime = getCLconfig.scheduleEndTime;
1242
- element4.scheduleEndTime_iso = endTimeIso.format();
1243
- element4.createdBy = new ObjectId( getCLconfig.createdBy );
1244
- element4.createdByName = getCLconfig.createdByName;
1245
- element4.sourceCheckList_id = getCLconfig._id;
1246
- element4.checkListType = getCLconfig.checkListType;
1247
- element4.storeCount = getCLconfig.storeCount;
1248
- element4.questionCount = getCLconfig.questionCount;
1249
- element4.publishDate = getCLconfig.publishDate;
1250
- element4.locationCount = getCLconfig.locationCount;
1251
- element4.scheduleRepeatedType = 'daily';
1252
- element4.approvalEnable = getCLconfig.approver.length ? true : false;
1253
- element4.priorityType = getCLconfig.priorityType;
1254
- element4.remainder = getCLconfig?.remainder || [];
1255
- element4.restrictAttendance = getCLconfig?.restrictAttendance;
1256
- element4.coverage = getCLconfig?.coverage;
1257
- assignUserList.push( element4 );
1258
- }
1259
- } ) );
963
+ continue;
964
+ }
965
+ delete element4._id;
966
+ delete element4.checkFlag;
967
+ delete element4.isdeleted;
968
+ delete element4.createdAt;
969
+ delete element4.updatedAt;
970
+ element4.checkListId = updatedchecklist._id;
971
+ element4.checkListName = getCLconfig.checkListName;
972
+ element4.checkListDescription = getCLconfig.checkListDescription;
973
+ element4.date_iso = new Date( dayjs( date, 'YYYY-MM-DD' ).format( 'YYYY-MM-DD' ) );
974
+ element4.date_string = dayjs( date ).format( 'YYYY-MM-DD' );
975
+ element4.allowedOverTime = false;
976
+ element4.allowedStoreLocation = getCLconfig.allowedStoreLocation;
977
+ element4.scheduleStartTime = '12:00 AM';
978
+ element4.scheduleStartTime_iso = startTimeIso.format();
979
+ element4.scheduleEndTime = getCLconfig.scheduleEndTime;
980
+ element4.scheduleEndTime_iso = endTimeIso.format();
981
+ element4.createdBy = new ObjectId( getCLconfig.createdBy );
982
+ element4.createdByName = getCLconfig.createdByName;
983
+ element4.sourceCheckList_id = getCLconfig._id;
984
+ element4.checkListType = getCLconfig.checkListType;
985
+ element4.storeCount = getCLconfig.storeCount;
986
+ element4.questionCount = getCLconfig.questionCount;
987
+ element4.publishDate = getCLconfig.publishDate;
988
+ element4.locationCount = getCLconfig.locationCount;
989
+ element4.scheduleRepeatedType = 'daily';
990
+ element4.approvalEnable = getCLconfig.approver.length ? true : false;
991
+ element4.priorityType = getCLconfig.priorityType;
992
+ element4.remainder = getCLconfig?.remainder || [];
993
+ element4.restrictAttendance = getCLconfig?.restrictAttendance;
994
+ }
1260
995
  if ( userIdList.length ) {
1261
- assignUserList = assignUserList.filter( ( item ) => typeof item._id == 'undefined' );
996
+ allQuestion = allQuestion.filter( ( item ) => typeof item._id == 'undefined' );
1262
997
  }
1263
998
 
1264
- if ( assignUserList ) {
999
+ if ( allQuestion ) {
1265
1000
  let assigndeletequery = {
1266
1001
  date_iso: date,
1267
1002
  client_id: insertdata.client_id,
@@ -1284,7 +1019,7 @@ async function insertPCBulkV3( getCLconfig, checklistId, updatedchecklist, date,
1284
1019
 
1285
1020
  const taskToRetain = await taskProcessedService.find( retainTaskQuery );
1286
1021
 
1287
- const insertList = assignUserList.filter( ( item2 ) =>
1022
+ const insertList = allQuestion.filter( ( item2 ) =>
1288
1023
  !taskToRetain.some( ( item1 ) =>
1289
1024
  item1.store_id === item2.store_id && item1.userEmail === item2.userEmail,
1290
1025
  ),
@@ -1350,7 +1085,6 @@ export async function uploadImage( req, res ) {
1350
1085
 
1351
1086
  async function createUser( data ) {
1352
1087
  try {
1353
- console.log( 'createUser ====>', data );
1354
1088
  let params = {
1355
1089
  userName: data.userName,
1356
1090
  email: data.email,
@@ -1433,8 +1167,7 @@ async function createUser( data ) {
1433
1167
  ],
1434
1168
  };
1435
1169
  let response = await userService.create( params );
1436
- // console.log( 'createUser ====>', response );
1437
- return response;
1170
+ return response._id;
1438
1171
  } catch ( e ) {
1439
1172
  logger.error( 'createUser =>', e );
1440
1173
  return false;
@@ -1634,17 +1367,16 @@ export async function createChecklistTask( req, res ) {
1634
1367
  client_id: inputBody.clientId,
1635
1368
  };
1636
1369
  await taskQuestionService.create( question );
1637
- let storeDetails;
1638
- if ( inputBody?.storeName ) {
1639
- storeDetails = await storeService.findOne( { storeName: inputBody.storeName, status: 'active' }, { storeId: 1, storeProfile: 1 } );
1370
+ let storeDetails = await storeService.findOne( { storeName: inputBody.storeName, status: 'active' }, { storeId: 1, storeProfile: 1 } );
1371
+ if ( !storeDetails ) {
1372
+ return res.sendError( 'No data found', 204 );
1640
1373
  }
1641
-
1642
1374
  let userDetails = {
1643
1375
  userName: inputBody.userName,
1644
1376
  userEmail: inputBody.userEmail,
1645
- store_id: storeDetails?.storeId?storeDetails.storeId:'',
1646
- storeName: inputBody?.storeName?inputBody?.storeName:'',
1647
- city: storeDetails?.storeProfile?.city?storeDetails?.storeProfile?.city:'',
1377
+ store_id: storeDetails.storeId,
1378
+ storeName: inputBody.storeName,
1379
+ city: storeDetails?.storeProfile?.city,
1648
1380
  checkFlag: true,
1649
1381
  checkListId: response?._id,
1650
1382
  checkListName: data.checkListName,
@@ -1663,9 +1395,8 @@ export async function createChecklistTask( req, res ) {
1663
1395
  if ( sectionIndex == -1 ) {
1664
1396
  return res.sendError( 'section is not found', 400 );
1665
1397
  }
1666
- let findQuestion = question[sectionIndex].questions.findIndex( ( ele ) => ele?.parentQuestion ? ele.qno == req.body.qno && ele.parentQuestion == req.body.parentQuestion : ele.qno == req.body.qno );
1398
+ let data = { ...question[sectionIndex].questions[req.body.qno - 1], taskId: response?._id, task: true };
1667
1399
 
1668
- let data = { ...question[sectionIndex].questions[findQuestion], taskId: response?._id, task: true };
1669
1400
  question[sectionIndex].questions[req.body.qno - 1] = data;
1670
1401
  taskDetails.questionAnswers = question;
1671
1402
  let updateData = {
@@ -1678,7 +1409,6 @@ export async function createChecklistTask( req, res ) {
1678
1409
  _id: inputBody.processedChecklistId,
1679
1410
  section_id: inputBody.sectionId,
1680
1411
  qno: inputBody.qno,
1681
- parentQuestion: inputBody.parentQuestion,
1682
1412
  },
1683
1413
  'upsert': {
1684
1414
  taskId: String( response?._id ),
@@ -1738,7 +1468,6 @@ export async function approveTask( req, res ) {
1738
1468
  sourceCheckList_id: req.body.sourceCheckList_id,
1739
1469
  fromDate: req.body.fromDate,
1740
1470
  toDate: req.body.toDate,
1741
- filtertype: req.body.filtertype,
1742
1471
  store_id: inputstores,
1743
1472
  },
1744
1473
  'upsert': {
@@ -1816,7 +1545,6 @@ export async function redoTask( req, res ) {
1816
1545
  };
1817
1546
 
1818
1547
  let response = await taskProcessedService.updateOne( { _id: req.body.payload._id }, updateData );
1819
- console.log( response );
1820
1548
  if ( response.modifiedCount || response.matchedCount ) {
1821
1549
  let storeTimeZone = await storeService.findOne( { storeName: taskDetails.storeName }, { 'storeProfile.timeZone': 1 } );
1822
1550
  let currentDateTime;
@@ -1833,8 +1561,8 @@ export async function redoTask( req, res ) {
1833
1561
  sectionName: question[sectionIndex].sectionName,
1834
1562
  questionName: question[sectionIndex].questions[req.body.payload.qno - 1].qname,
1835
1563
  action: 'redo',
1836
- store_id: taskDetails?.store_id?taskDetails?.store_id:'',
1837
- storeName: taskDetails.storeName?taskDetails.storeName:'',
1564
+ store_id: taskDetails.store_id,
1565
+ storeName: taskDetails.storeName,
1838
1566
  client_id: taskDetails.client_id,
1839
1567
  processedChecklistId: taskDetails._id,
1840
1568
  type: taskDetails.checkListType,
@@ -1856,7 +1584,6 @@ export async function redoTask( req, res ) {
1856
1584
  };
1857
1585
  let url = JSON.parse( process.env.LAMBDAURL );
1858
1586
  let searchResponse = await fetch( url.redoTask, requestOptions );
1859
- console.log( searchResponse.ok );
1860
1587
  if ( searchResponse.ok ) {
1861
1588
  return res.sendSuccess( 'Question redo successfully' );
1862
1589
  } else {
@@ -1929,19 +1656,15 @@ export async function getAnswerCount( req, res ) {
1929
1656
  export const taskDropdown = async ( req, res ) => {
1930
1657
  try {
1931
1658
  let requestData = req.body;
1932
- let fromDate = new Date( requestData.fromDate );
1933
- let toDate = new Date( requestData.toDate );
1934
- let userTimezoneOffset = toDate.getTimezoneOffset() * 60000;
1935
- toDate = new Date( toDate.getTime() - userTimezoneOffset );
1936
- toDate.setUTCHours( 23, 59, 59, 59 );
1659
+
1937
1660
  let result = {};
1938
1661
 
1939
1662
  let findQuery = [];
1940
1663
  let findAndQuery = [];
1941
1664
  findAndQuery.push(
1942
1665
  { client_id: requestData.clientId },
1943
- { date_iso: { $gte: fromDate } },
1944
- { date_iso: { $lte: toDate } },
1666
+ // { date_iso: { $gte: fromDate } },
1667
+ // { date_iso: { $lte: toDate } },
1945
1668
  { checkListType: { $in: [ 'task', 'checklistTask', 'cctv' ] } },
1946
1669
  );
1947
1670
 
@@ -1957,7 +1680,6 @@ export const taskDropdown = async ( req, res ) => {
1957
1680
  scheduleRepeatedType: 1,
1958
1681
  scheduleStartTime: 1,
1959
1682
  scheduleEndTime: 1,
1960
- coverage: 1,
1961
1683
  },
1962
1684
  } );
1963
1685
 
@@ -1972,7 +1694,6 @@ export const taskDropdown = async ( req, res ) => {
1972
1694
  scheduleRepeatedType: { $last: '$scheduleRepeatedType' },
1973
1695
  scheduleStartTime: { $last: '$scheduleStartTime' },
1974
1696
  scheduleEndTime: { $last: '$scheduleEndTime' },
1975
- coverage: { $last: '$coverage' },
1976
1697
  },
1977
1698
  } );
1978
1699
 
@@ -2011,7 +1732,6 @@ export const taskDropdown = async ( req, res ) => {
2011
1732
  scheduleRepeatedType: 1,
2012
1733
  scheduleStartTime: 1,
2013
1734
  scheduleEndTime: 1,
2014
- coverage: 1,
2015
1735
  checkListDescription: '$checklistconfigs.checkListDescription',
2016
1736
  publish: '$checklistconfigs.publish',
2017
1737
  },
@@ -2447,13 +2167,13 @@ export async function clusterMigrations( req, res ) {
2447
2167
  if ( userexits ) {
2448
2168
  let findStore = await storeService.findOne( { storeName: user.FacilityCode } );
2449
2169
  if ( findStore ) {
2450
- let clusterExists = await clusterServices.findOneCluster( { clusterName: user.AomName } );
2170
+ let clusterExists = await clusterModel.findOneCluster( { clusterName: user.AomName } );
2451
2171
  if ( clusterExists ) {
2452
2172
  let data = {
2453
2173
  storeId: findStore.storeId,
2454
2174
  store: findStore._id,
2455
2175
  };
2456
- let updatecluster = await clusterServices.updateCluster( { clusterName: user.AomName }, { $push: { stores: data } } );
2176
+ let updatecluster = await clusterModel.updateCluster( { clusterName: user.AomName }, { $push: { stores: data } } );
2457
2177
  console.log( updatecluster );
2458
2178
  } else {
2459
2179
  let payload = {
@@ -2475,7 +2195,7 @@ export async function clusterMigrations( req, res ) {
2475
2195
  ],
2476
2196
  'users': [],
2477
2197
  };
2478
- let createcluster = await clusterServices.createclusterModel( payload );
2198
+ let createcluster = await clusterModel.createclusterModel( payload );
2479
2199
  console.log( createcluster );
2480
2200
  }
2481
2201
  }
@@ -2860,216 +2580,9 @@ export async function StoreHygienetask( req, res ) {
2860
2580
  return res.sendError( e, 500 );
2861
2581
  }
2862
2582
  }
2863
- export async function commonAiTask( req, res ) {
2864
- try {
2865
- let inputBody = req.body;
2866
-
2867
- inputBody.clientId = 11;
2868
- inputBody.taskDescription = '';
2869
- let userId;
2870
- let storeDetails = await storeService.findOne( { storeName: inputBody.storeName, clientId: inputBody.clientId, status: 'active' }, { storeId: 1, storeName: 1, storeProfile: 1 } );
2871
- if ( !storeDetails ) {
2872
- return res.sendError( 'Store Not Found', 500 );
2873
- }
2874
-
2875
- let url = JSON.parse( process.env.LAMBDAURL );
2876
- let checklistId = url.dailystoreChecklistId;
2877
- let finduser = await checklistassignconfigModel.findOne( { checkListId: new mongoose.Types.ObjectId( checklistId ), store_id: storeDetails.storeId } );
2878
-
2879
- if ( !finduser ) {
2880
- return res.sendError( 'No user Found For this store', 500 );
2881
- }
2882
-
2883
- userId = finduser.userId;
2884
- inputBody.userName = finduser.userName;
2885
- inputBody.userEmail = finduser.userEmail;
2886
-
2887
-
2888
- let teamList = await findteams( { users: { $elemMatch: { email: finduser.userEmail } } } );
2889
-
2890
- inputBody.approver = '';
2891
- for ( let team of teamList ) {
2892
- for ( let user of team.Teamlead ) {
2893
- inputBody.approver = user.email + ',' + inputBody.approver;
2894
- }
2895
- }
2896
- inputBody.approver = inputBody.approver.replace( /,$/, '' );
2897
-
2898
-
2899
- let title = `New Task Alert ${inputBody.taskName}-${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}`;
2900
- let time = inputBody?.scheduleEndTime || '11:59 PM';
2901
- let date = inputBody?.scheduleDate || dayjs().format( 'YYYY-MM-DD' );
2902
- let description = `A new task has been assigned to ${storeDetails.storeName}. Please complete it before the due date of ${date}.`;
2903
- if ( userDetails&&userDetails.fcmToken ) {
2904
- const fcmToken = userDetails.fcmToken;
2905
- await sendPushNotification( title, description, fcmToken );
2906
- }
2907
- const inputDateTime = dayjs.utc( `${date} ${time}`, 'YYYY-MM-DD hh:mm A' );
2908
- const currentTime = dayjs.utc();
2909
- if ( inputDateTime.isBefore( currentTime ) ) {
2910
- return res.sendError( 'The input date-time is before the current time.', 500 );
2911
- }
2912
-
2913
- let approverList = inputBody?.approver.split( ',' );
2914
-
2915
-
2916
- let userAdmin = await userService.find( { clientId: inputBody.clientId, email: { $in: approverList }, userType: 'client', isActive: true }, { name: '$userName', email: 1 } );
2917
-
2918
- if ( userAdmin && userAdmin.length === 0 ) {
2919
- userAdmin = await userService.find( { clientId: inputBody.clientId, email: 'rohit.chawla@lenskart.com', userType: 'client', isActive: true }, { name: '$userName', email: 1 } );
2920
- }
2921
-
2922
- let creator = await userService.find( { clientId: inputBody.clientId, email: 'rohit.chawla@lenskart.com', userType: 'client', isActive: true } );
2923
- if ( creator && creator.length === 0 ) {
2924
- return res.sendError( 'Invalid Creator Details', 500 );
2925
- }
2926
-
2927
- if ( req.body && req.body.referenceImage && req.body.referenceImage.length > 3 ) {
2928
- return res.sendError( 'Maximum 3 referenceImage only allowed', 500 );
2929
- }
2930
- let data = {
2931
- checkListName: `${inputBody.taskName}(${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )})`,
2932
- checkListDescription: inputBody.taskDescription,
2933
- createdBy: creator[0]._id,
2934
- createdByName: creator[0].userName,
2935
- publish: true,
2936
- questionCount: 1,
2937
- storeCount: 1,
2938
- scheduleDate: date,
2939
- scheduleEndTime: time,
2940
- scheduleEndTimeISO: dayjs.utc( `${date} ${time}`, 'YYYY-MM-DD hh:mm A' ).format(),
2941
- priorityType: 'high',
2942
- client_id: inputBody.clientId,
2943
- checkListType: 'task',
2944
- publishDate: new Date(),
2945
- locationCount: 1,
2946
- ...( inputBody?.checkListId ) ? { referenceCheckListId: inputBody?.checkListId } : {},
2947
- };
2948
- data['approver'] = userAdmin;
2949
- let answer = await findAnswer( inputBody?.answerType );
2950
- if ( answer.length == 0 ) {
2951
- return res.sendError( 'please enter Valid AnswerType', 500 );
2952
- }
2953
- if ( inputBody?.answerType === 'multiplechoicesingle' || inputBody?.answerType === 'multiplechoicemultiple' ) {
2954
- if ( inputBody?.options && inputBody?.options.length > 0 ) {
2955
- let optionsResult = [];
2956
- let optionList = inputBody?.options.split( ',' );
2957
- for ( let option of optionList ) {
2958
- let optiondata = {
2959
- 'answer': '',
2960
- 'sopFlag': false,
2961
- 'validation': false,
2962
- 'validationType': '',
2963
- 'referenceImage': [],
2964
- 'runAI': false,
2965
- 'allowUploadfromGallery': false,
2966
- 'descriptivetype': '',
2967
- 'showLinked': false,
2968
- 'linkedQuestion': 0,
2969
- 'nestedQuestion': [],
2970
- };
2971
- optiondata.answer = option;
2972
- optionsResult.push( optiondata );
2973
- }
2974
- answer = optionsResult;
2975
- } else {
2976
- return res.sendError( 'please enter Valid Options', 500 );
2977
- }
2978
- }
2979
- let response = await taskService.create( data );
2980
- if ( response?.approver.length ) {
2981
- let inputData = [];
2982
- response?.approver.forEach( ( ele ) => {
2983
- inputData.push( {
2984
- userEmail: ele.email,
2985
- checkListId: response._id,
2986
- type: 'task',
2987
- client_id: inputBody.clientId,
2988
- checkListName: data?.checkListName || '',
2989
- } );
2990
- } );
2991
- await traxApprover.insertMany( inputData );
2992
- }
2993
- if ( response?._id ) {
2994
- let question = [
2995
- {
2996
- 'qno': 1,
2997
- 'qname': inputBody.question,
2998
- 'answerType': inputBody?.answerType || 'yes/no',
2999
- 'runAI': false,
3000
- 'runAIDescription': '',
3001
- 'allowUploadfromGallery': false,
3002
- 'linkType': false,
3003
- 'questionReferenceImage': [],
3004
- 'answers': answer,
3005
- 'descriptivetype': 'text',
3006
- },
3007
- ];
3008
- let images = [];
3009
- for ( let imgpath of req.body.referenceImage ) {
3010
- let configURL = JSON.parse( process.env.BUCKET );
3011
- let inputData = {
3012
- Bucket: configURL.commonAiTaskBucket,
3013
- Key: imgpath,
3014
- };
3015
- let output = await getObject( inputData );
3016
- console.log( output );
3017
-
3018
- let image = {
3019
- data: output.Body,
3020
- name: imgpath,
3021
- mimetype: output.ContentType,
3022
- };
3023
- let uplaodedImage = await uploadmultiImage( image );
3024
-
3025
- let imgUrl = decodeURIComponent( uplaodedImage.imgUrl.split( '?' )[0] );
3026
- let url = imgUrl.split( '/' );
3027
- if ( url.includes( 'https:' ) || url.includes( 'http:' ) ) {
3028
- url.splice( 0, 3 );
3029
- }
3030
- images.push( url.join( '/' ) );
3031
- }
3032
- question[0].questionReferenceImage = images;
3033
-
3034
- if ( inputBody?.answerType === 'image' || inputBody?.answerType === 'descriptiveImage' || inputBody?.answerType === 'multipleImage' ) {
3035
- answer[0].referenceImage = question[0].questionReferenceImage;
3036
- }
3037
-
3038
-
3039
- question = {
3040
- checkListId: response?._id,
3041
- question: question,
3042
- section: 'Section 1',
3043
- checkList: data.checkListName,
3044
- client_id: inputBody.clientId,
3045
- };
3046
- await taskQuestionService.create( question );
3047
-
3048
- let userDetails = {
3049
- userName: inputBody.userName,
3050
- userEmail: inputBody.userEmail,
3051
- store_id: storeDetails.storeId,
3052
- storeName: storeDetails.storeName,
3053
- city: storeDetails?.storeProfile?.city,
3054
- checkFlag: true,
3055
- checkListId: response?._id,
3056
- checkListName: data.checkListName,
3057
- client_id: inputBody.clientId,
3058
- userId: userId,
3059
- };
3060
- await taskAssignService.create( userDetails );
3061
- await insertSingleProcessData( response?._id );
3062
- return res.sendSuccess( 'Task created successfully' );
3063
- }
3064
- } catch ( e ) {
3065
- logger.error( { function: 'commonAiTask', error: e } );
3066
- return res.sendError( e, 500 );
3067
- }
3068
- }
3069
2583
  export async function eyeTesttask( req, res ) {
3070
2584
  try {
3071
2585
  let inputBody = req.body;
3072
- console.log( inputBody );
3073
2586
  inputBody.clientId = 11;
3074
2587
  inputBody.taskDescription = '';
3075
2588
  let userId;
@@ -3080,9 +2593,7 @@ export async function eyeTesttask( req, res ) {
3080
2593
 
3081
2594
  let url = JSON.parse( process.env.LAMBDAURL );
3082
2595
  let checklistId = url.dailystoreChecklistId;
3083
- console.log( checklistId );
3084
2596
  let finduser = await checklistassignconfigModel.findOne( { checkListId: new mongoose.Types.ObjectId( checklistId ), store_id: storeDetails.storeId } );
3085
- console.log( finduser );
3086
2597
 
3087
2598
  if ( !finduser ) {
3088
2599
  return res.sendError( 'No user Found For this store', 500 );
@@ -3241,10 +2752,8 @@ export async function eyeTesttask( req, res ) {
3241
2752
  }
3242
2753
  question[0].questionReferenceImage = images;
3243
2754
  } else {
3244
- console.log( req.file );
3245
2755
  let images = [];
3246
2756
  let uplaodedImage = await uploadmultiImage( req.files.referenceImage );
3247
- console.log( uplaodedImage );
3248
2757
  let imgUrl = decodeURIComponent( uplaodedImage.imgUrl.split( '?' )[0] );
3249
2758
  let url = imgUrl.split( '/' );
3250
2759
  if ( url.includes( 'https:' ) || url.includes( 'http:' ) ) {
@@ -3313,14 +2822,14 @@ export async function createAiTask( req, res ) {
3313
2822
  inputBody.userEmail = finduser.userEmail;
3314
2823
 
3315
2824
 
3316
- let title = `New Task Alert ${inputBody.taskName}-${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}`;
2825
+ // let title = `New Task Alert ${inputBody.taskName}-${storeDetails.storeName}-${dayjs().format( 'YYYY-MM-DD' )}`;
3317
2826
  let time = inputBody?.scheduleEndTime || '11:59 PM';
3318
2827
  let date = inputBody?.scheduleDate || dayjs().format( 'YYYY-MM-DD' );
3319
- let description = `A new task has been assigned to ${storeDetails.storeName}. Please complete it before the due date of ${date}.`;
3320
- if ( userDetails&&userDetails.fcmToken ) {
3321
- const fcmToken = userDetails.fcmToken;
3322
- await sendPushNotification( title, description, fcmToken );
3323
- }
2828
+ // let description = `A new task has been assigned to ${storeDetails.storeName}. Please complete it before the due date of ${date}.`;
2829
+ // if ( userDetails&&userDetails.fcmToken ) {
2830
+ // const fcmToken = userDetails.fcmToken;
2831
+ // await sendPushNotification( title, description, fcmToken );
2832
+ // }
3324
2833
  const inputDateTime = dayjs.utc( `${date} ${time}`, 'YYYY-MM-DD hh:mm A' );
3325
2834
  const currentTime = dayjs.utc();
3326
2835
  if ( inputDateTime.isBefore( currentTime ) ) {
@@ -3758,43 +3267,6 @@ export async function uploadmultiImage( images ) {
3758
3267
  }
3759
3268
  };
3760
3269
 
3761
- async function assignUsers( data ) {
3762
- let assignedData;
3763
- if ( data?.type == 'cluster' ) {
3764
- let clusterDetails = await clusterServices.findcluster( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3765
- if ( clusterDetails.length ) {
3766
- let clusterList = clusterDetails[0].stores.map( ( ele ) => ele.store );
3767
- let storeDetails = await storeService.find( { _id: { $in: clusterList }, status: 'active' } );
3768
- assignedData = await Promise.all( storeDetails.map( async ( store ) => {
3769
- let userData = {
3770
- storeId: store.storeId,
3771
- storeName: store.storeName,
3772
- userName: store.spocDetails?.[0]?.name,
3773
- userEmail: store.spocDetails?.[0]?.email,
3774
- clusterName: clusterDetails?.[0]?.clusterName,
3775
- id: clusterDetails?.[0]?._id,
3776
- };
3777
- return userData;
3778
- } ) );
3779
- }
3780
- } else {
3781
- let teamDetails = await teamsServices.findteams( { clientId: data.clientId, _id: new mongoose.Types.ObjectId( data.id ) } );
3782
- if ( teamDetails.length ) {
3783
- let userIdList = teamDetails[0].users.map( ( ele ) => ele.userId );
3784
- let userDetails = await userService.find( { _id: userIdList } );
3785
- assignedData = userDetails.map( ( user ) => {
3786
- let userData = {
3787
- userName: user.userName,
3788
- userEmail: user.email,
3789
- teamName: teamDetails?.[0]?.teamName,
3790
- id: teamDetails?.[0]?._id,
3791
- };
3792
- return userData;
3793
- } );
3794
- }
3795
- }
3796
- return assignedData;
3797
- }
3798
3270
 
3799
3271
  export async function customertrial( params ) {
3800
3272
  try {
@@ -3820,145 +3292,3 @@ export async function customertrial( params ) {
3820
3292
  }
3821
3293
  };
3822
3294
 
3823
- export async function taskAssign( req, res ) {
3824
- try {
3825
- if ( !req.body.taskId ) {
3826
- return res.sendError( 'task id is required', 400 );
3827
- }
3828
- if ( !req.body.coverage ) {
3829
- return res.sendError( 'Coverage is required', 400 );
3830
- }
3831
- if ( !req.body.idList ) {
3832
- return res.sendError( 'Id is required', 400 );
3833
- }
3834
-
3835
- let taskDetails = await taskService.findOne( { _id: req.body.taskId } );
3836
- if ( !taskDetails ) {
3837
- return res.sendError( 'No data found', 204 );
3838
- }
3839
-
3840
- let uniqueArr = [];
3841
-
3842
- await Promise.all( req.body.idList.map( async ( data ) => {
3843
- let assignedData = {
3844
- ...data,
3845
- clientId: req.body.clientId,
3846
- };
3847
- let uploadData = await assignUsers( assignedData );
3848
- if ( uploadData?.length ) {
3849
- uniqueArr.push( ...uploadData );
3850
- }
3851
- } ) );
3852
-
3853
- if ( uniqueArr.length ) {
3854
- if ( req.body.coverage == 'store' ) {
3855
- uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3856
- if ( acc[obj.storeName] ) {
3857
- acc[obj.storeName].clusterName += ',' + obj.clusterName;
3858
- } else {
3859
- acc[obj.storeName] = { ...obj };
3860
- }
3861
- return acc;
3862
- }, {} );
3863
-
3864
- uniqueArr= Object.values( uniqueArr );
3865
- } else {
3866
- uniqueArr = uniqueArr.reduce( ( acc, obj ) => {
3867
- if ( acc[obj.userEmail] ) {
3868
- acc[obj.userEmail].teamName += ','+ obj.teamName;
3869
- } else {
3870
- acc[obj.userEmail] = { ...obj };
3871
- }
3872
- return acc;
3873
- }, {} );
3874
- uniqueArr = Object.values( uniqueArr );
3875
- }
3876
- }
3877
-
3878
- return res.sendSuccess( { count: uniqueArr.length, uniqueArr } );
3879
- } catch ( e ) {
3880
- logger.error( { functionName: 'taskAssign', error: e } );
3881
- return res.sendError( e, 500 );
3882
- }
3883
- }
3884
-
3885
- export async function updateAssign( req, res ) {
3886
- try {
3887
- // if ( !req.body.assignedList.length && !req.body.assignedGroup.length ) {
3888
- // return res.sendError( 'No data found', 204 );
3889
- // }
3890
- let taskDetails = await taskService.findOne( { _id: req.body.taskId, client_id: req.body.clientId } );
3891
- if ( !taskDetails ) {
3892
- return res.sendError( 'No data found', 204 );
3893
- }
3894
- req.body.assignedGroup = [ ...new Set( req.body.assignedGroup.map( ( item ) => item.id ) ) ];
3895
- req.body.assignedGroup = req.body.assignedGroup.map( ( ele ) => {
3896
- return { id: ele };
3897
- } );
3898
- await taskAssignService.deleteMany( { checkListId: req.body.taskId } );
3899
- let assignedUserList = [];
3900
- await Promise.all( req.body.assignedList.map( async ( assign ) => {
3901
- let query = [
3902
- {
3903
- $addFields: {
3904
- emailToLower: { $toLower: '$email' },
3905
- },
3906
- },
3907
- {
3908
- $match: {
3909
- clientId: req.body.clientId,
3910
- emailToLower: assign.userEmail.toLowerCase(),
3911
- },
3912
- },
3913
- ];
3914
- let userDetails = await userService.aggregate( query );
3915
- if ( !userDetails.length ) {
3916
- let userData = {
3917
- userName: assign.userName,
3918
- email: assign.userEmail,
3919
- mobileNumber: assign?.phone || '',
3920
- clientId: req.body.clientId,
3921
- };
3922
- userDetails = await createUser( userData );
3923
- userDetails = [ userDetails ];
3924
- }
3925
- let data = {
3926
- ...assign,
3927
- store_id: assign?.storeId,
3928
- client_id: req.body.clientId,
3929
- checkListId: req.body.taskId,
3930
- coverage: req.body.coverage,
3931
- assignId: assign._id,
3932
- userId: userDetails?.[0]?._id,
3933
- checkListName: taskDetails.checkListName,
3934
- };
3935
- delete data._id;
3936
- assignedUserList.push( data );
3937
- } ) );
3938
- await Promise.all( req.body.assignedGroup.map( async ( assign ) => {
3939
- let groupDetails;
3940
- if ( req.body.coverage == 'store' ) {
3941
- groupDetails = await clusterServices.findOneCluster( { _id: assign.id } );
3942
- } else {
3943
- groupDetails = await teamsServices.findOneTeams( { _id: assign.id } );
3944
- }
3945
- if ( groupDetails ) {
3946
- let groupData = {
3947
- client_id: req.body.clientId,
3948
- checkListId: req.body.taskId,
3949
- coverage: req.body.coverage,
3950
- assignId: assign.id,
3951
- checkListName: taskDetails.checkListName,
3952
- ...( req.body.coverage == 'store' ) ? { clusterName: groupDetails?.clusterName } : { teamName: groupDetails?.teamName },
3953
- };
3954
- assignedUserList.push( groupData );
3955
- }
3956
- } ) );
3957
- await taskAssignService.insertMany( assignedUserList );
3958
- return res.sendSuccess( 'Assign details updated successfully' );
3959
- } catch ( e ) {
3960
- logger.error( { functionName: 'updateAssign', error: e } );
3961
- return res.sendError( e, 500 );
3962
- }
3963
- }
3964
-