tango-app-api-audit 1.0.15 → 1.0.16

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-audit",
3
- "version": "1.0.15",
3
+ "version": "1.0.16",
4
4
  "description": "audit & audit metrics apis",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -1,18 +1,55 @@
1
- import { chunkArray, download, getJsonFileData, getUTC, insertOpenSearchData, listFileByPath, listFileWithoutLimit, signedUrl } from 'tango-app-api-middleware';
2
- import { aggregateUserAudit, createUserAudit, findOneUserAudit, updateOneUserAudit } from '../service/userAudit.service.js';
3
- import { aggregateAssignAudit, updateOneAssignAudit } from '../service/assignAudit.service.js';
1
+ import {
2
+ chunkArray,
3
+ download,
4
+ fileUpload,
5
+ getJsonFileData,
6
+ getUTC,
7
+ insertOpenSearchData,
8
+ listFileByPath,
9
+ listFileWithoutLimit,
10
+ signedUrl,
11
+ } from 'tango-app-api-middleware';
12
+ import {
13
+ aggregateUserAudit,
14
+ createUserAudit,
15
+ findOneUserAudit,
16
+ updateOneUserAudit,
17
+ } from '../service/userAudit.service.js';
18
+ import {
19
+ aggregateAssignAudit,
20
+ updateOneAssignAudit,
21
+ } from '../service/assignAudit.service.js';
4
22
  import { findOneUser } from '../service/user.service.js';
5
23
  import dayjs from 'dayjs';
6
- import { aggregateClient } from '../service/client.service.js';
24
+ import { aggregateClient, findClient } from '../service/client.service.js';
7
25
  import { logger } from 'tango-app-api-middleware';
8
- import { listQueue, sqsReceive } from 'tango-app-api-middleware/src/utils/aws/sqs.js';
9
- import { aggregateStoreAudit, createStoreAudit, updateOneStoreAudit } from '../service/storeAudit.service.js';
26
+ import {
27
+ listQueue,
28
+ sqsReceive,
29
+ sendMessageToQueue,
30
+ } from 'tango-app-api-middleware/src/utils/aws/sqs.js';
31
+ import {
32
+ aggregateStoreAudit,
33
+ createStoreAudit,
34
+ findOneStoreAudit,
35
+ updateOneStoreAudit,
36
+ } from '../service/storeAudit.service.js';
10
37
  import { aggregateAuditClientData } from '../service/auditClientData.service.js';
11
38
  import _ from 'lodash';
12
- import { createAuditLog, findOneAuditLog } from '../service/auditLog.service.js';
39
+ import {
40
+ createAuditLog,
41
+ findOneAuditLog,
42
+ } from '../service/auditLog.service.js';
13
43
  import { findOneStore } from '../service/store.service.js';
14
- import { mapCustomer, mapEmployee, mapJunk, splitB20000, splitE0, splitG20000 } from '../validation/audit.validation.js';
15
-
44
+ import {
45
+ mapCustomer,
46
+ mapEmployee,
47
+ mapJunk,
48
+ splitB20000,
49
+ splitE0,
50
+ splitG20000,
51
+ } from '../validation/audit.validation.js';
52
+ import mongoose from 'mongoose';
16
53
  export async function getAuditFile( req, res ) {
17
54
  try {
18
55
  const bucket = JSON.parse( process.env.BUCKET );
@@ -33,9 +70,7 @@ export async function getAuditFile( req, res ) {
33
70
  { createdAt: { $gte: start } },
34
71
  { createdAt: { $lte: end } },
35
72
  ],
36
-
37
73
  },
38
-
39
74
  },
40
75
  {
41
76
  $sort: { createdAt: -1 },
@@ -46,7 +81,8 @@ export async function getAuditFile( req, res ) {
46
81
  ];
47
82
 
48
83
  const userDetails = await aggregateUserAudit( userQuery );
49
- const auditStatus = userDetails && userDetails.length > 0 ? userDetails[0].auditStatus : null;
84
+ const auditStatus =
85
+ userDetails && userDetails.length > 0 ? userDetails[0].auditStatus : null;
50
86
 
51
87
  switch ( auditStatus ) {
52
88
  case null:
@@ -64,24 +100,35 @@ export async function getAuditFile( req, res ) {
64
100
  const userAssign = await aggregateAssignAudit( query );
65
101
  if ( userAssign.length > 0 ) {
66
102
  logger.info( 'Hit in user assign', { inputData } );
67
- userAssign[0].fileType == 'Audit' ?
68
- msg = {
103
+ userAssign[0].fileType == 'Audit' ?
104
+ ( msg = {
69
105
  store_id: userAssign[0].storeId,
70
106
  curr_date: userAssign[0].fileDate,
71
107
  total_count: userAssign[0].fileCount,
72
- } : msg = {
108
+ } ) :
109
+ ( msg = {
73
110
  store_id: userAssign[0].storeId,
74
111
  curr_date: userAssign[0].fileDate,
75
112
  audit_type: userAssign[0].fileType,
76
113
  total_count: userAssign[0].fileCount,
77
- };
78
- await updateOneAssignAudit( { _id: userAssign[0]._id }, { isCompleted: true } );
79
- logger.info( 'Hit in auditUserAssignModel updateOne', { _id: userAssign[0]._id, isCompleted: true } );
114
+ } );
115
+ await updateOneAssignAudit(
116
+ { _id: userAssign[0]._id },
117
+ { isCompleted: true },
118
+ );
119
+ logger.info( 'Hit in auditUserAssignModel updateOne', {
120
+ _id: userAssign[0]._id,
121
+ isCompleted: true,
122
+ } );
80
123
  } else {
81
124
  logger.info( 'Hit in new file', { inputData } );
82
125
  const consumer = await sqsReceive( inputData.queueName );
83
126
  if ( !consumer ) {
84
- logger.error( { error: consumer, function: 'getAuditFile', message: 'SQS Receive queue is empty' } );
127
+ logger.error( {
128
+ error: consumer,
129
+ function: 'getAuditFile',
130
+ message: 'SQS Receive queue is empty',
131
+ } );
85
132
  return res.sendError( `${inputData.queueName} is Empty`, 204 );
86
133
  }
87
134
  msg = JSON.parse( consumer );
@@ -90,15 +137,26 @@ export async function getAuditFile( req, res ) {
90
137
 
91
138
  case 'drafted':
92
139
  logger.info( 'userDetails drafted', { inputData } );
93
- const log = await findOneAuditLog( {
94
- userId: userDetails[0].userId,
95
- fileDate: userDetails[0].fileDate,
96
- storeId: userDetails[0].storeId,
97
- totalCount: userDetails[0].beforeCount,
98
- }, {}, { createdAt: -1 } );
140
+ const log = await findOneAuditLog(
141
+ {
142
+ userId: userDetails[0].userId,
143
+ fileDate: userDetails[0].fileDate,
144
+ storeId: userDetails[0].storeId,
145
+ totalCount: userDetails[0].beforeCount,
146
+ },
147
+ {},
148
+ { createdAt: -1 },
149
+ );
99
150
  if ( !log ) {
100
- await updateOneUserAudit( { _id: userDetails[0]._id }, { $set: { isDraft: false, auditStatus: 'skipped' } } );
101
- logger.info( 'audit update in drafted', { _id: userDetails[0]._id, isDraft: false, auditStatus: 'skipped' } );
151
+ await updateOneUserAudit(
152
+ { _id: userDetails[0]._id },
153
+ { $set: { isDraft: false, auditStatus: 'skipped' } },
154
+ );
155
+ logger.info( 'audit update in drafted', {
156
+ _id: userDetails[0]._id,
157
+ isDraft: false,
158
+ auditStatus: 'skipped',
159
+ } );
102
160
  return res.sendError( 'User saved data has been deleted', 204 );
103
161
  }
104
162
  const file = {
@@ -122,7 +180,11 @@ export async function getAuditFile( req, res ) {
122
180
  };
123
181
 
124
182
  const userdata = await findOneUser( { _id: log.userId } );
125
- if ( !inputData.nextId || inputData.nextId === '' || inputData.nextId == null ) {
183
+ if (
184
+ !inputData.nextId ||
185
+ inputData.nextId === '' ||
186
+ inputData.nextId == null
187
+ ) {
126
188
  const logData = {
127
189
  userId: log.userId,
128
190
  userName: userdata.name,
@@ -169,10 +231,7 @@ export async function getAuditFile( req, res ) {
169
231
  break;
170
232
  }
171
233
  if ( msg.audit_type === 'ReAudit' ) {
172
- logger.info(
173
- 'Hit in user ReAudit'
174
- , { inputData },
175
- );
234
+ logger.info( 'Hit in user ReAudit', { inputData } );
176
235
  let reauditInsert = {};
177
236
  const [ filterData, auditImage ] = await Promise.all( [
178
237
  getFilterData( msg ),
@@ -246,24 +305,22 @@ export async function getAuditFile( req, res ) {
246
305
  address: '$storeProfile.address',
247
306
  };
248
307
  const storeInfo = await findOneStore( storeQuery, storeFields );
249
- return res.sendSuccess(
250
- {
251
- result: reauditImg,
252
- count: reauditImg.length,
253
- storeId: storeInfo?.storeId,
254
- storeName: storeInfo?.storeName,
255
- address: storeInfo?.address || '',
256
- file: {
257
- store_id: msg.store_id,
258
- file_date: msg.curr_date,
259
- type: msg.audit_type || 'ReAudit',
260
- queueName: inputData.queueName,
261
- auditId: reauditInsert._id,
262
- userId: reauditInsert.userId,
263
- },
264
- isDraft: reauditInsert.isDraft,
265
- },
266
- );
308
+ return res.sendSuccess( {
309
+ result: reauditImg,
310
+ count: reauditImg.length,
311
+ storeId: storeInfo?.storeId,
312
+ storeName: storeInfo?.storeName,
313
+ address: storeInfo?.address || '',
314
+ file: {
315
+ store_id: msg.store_id,
316
+ file_date: msg.curr_date,
317
+ type: msg.audit_type || 'ReAudit',
318
+ queueName: inputData.queueName,
319
+ auditId: reauditInsert._id,
320
+ userId: reauditInsert.userId,
321
+ },
322
+ isDraft: reauditInsert.isDraft,
323
+ } );
267
324
  }
268
325
  const storeId = msg.store_id;
269
326
  const fileDate = msg.curr_date;
@@ -343,7 +400,11 @@ export async function getAuditFile( req, res ) {
343
400
  insertData = userDetails[0];
344
401
  }
345
402
  } else {
346
- logger.error( { error: { folderPath: folderPath, nextQuery: nextQuery }, function: 'getAuditFile', message: 'Bucket image data not availale' } );
403
+ logger.error( {
404
+ error: { folderPath: folderPath, nextQuery: nextQuery },
405
+ function: 'getAuditFile',
406
+ message: 'Bucket image data not availale',
407
+ } );
347
408
  return res.sendError( 'Bucket is Empty', 204 );
348
409
  }
349
410
  const userdata = await findOneUser( { _id: insertData.userId } );
@@ -390,7 +451,11 @@ export async function getAuditFile( req, res ) {
390
451
  isDraft: insertData.isDraft,
391
452
  } );
392
453
  } catch ( error ) {
393
- logger.error( { error: error, message: req.query, function: 'getAuditFile' } );
454
+ logger.error( {
455
+ error: error,
456
+ message: req.query,
457
+ function: 'getAuditFile',
458
+ } );
394
459
  return res.sendError( error, 500 );
395
460
  }
396
461
  }
@@ -407,17 +472,26 @@ export async function getFilterData( msg ) {
407
472
  return mappingFile;
408
473
  } else {
409
474
  const mappingData = await JSON.parse( mappingFile.toString( 'utf-8' ) );
410
- const filterData = await mappingData.person_data.filter( ( item ) => item.temp_ids < 20000 && item.temp_ids > 0 && item.person_status === '' );
475
+ const filterData = await mappingData.person_data.filter(
476
+ ( item ) =>
477
+ item.temp_ids < 20000 &&
478
+ item.temp_ids > 0 &&
479
+ item.person_status === '',
480
+ );
411
481
  const finalResult = await filterData.map( ( i ) => {
412
482
  return { ...i, img: i.index.concat( '_', i.temp_ids ) };
413
483
  } );
414
484
  return finalResult;
415
485
  }
416
486
  } catch ( error ) {
417
- logger.error( { error: error, type: 'MAPPING JSON getFilterData', function: 'getFilterData' } );
487
+ logger.error( {
488
+ error: error,
489
+ type: 'MAPPING JSON getFilterData',
490
+ function: 'getFilterData',
491
+ } );
418
492
  return error;
419
493
  }
420
- };
494
+ }
421
495
 
422
496
  export async function getAuditImage( msg ) {
423
497
  try {
@@ -464,7 +538,7 @@ export async function getAuditImage( msg ) {
464
538
  logger.error( { error: error, type: 'GCP BUCKET --getAuditImage' } );
465
539
  return error;
466
540
  }
467
- };
541
+ }
468
542
 
469
543
  export const getReauditImg = async ( filter, image ) => {
470
544
  const chunkedMappingData = await chunkArray( image, 10 );
@@ -491,7 +565,9 @@ export async function workSpace( req, res ) {
491
565
  try {
492
566
  const inputData = req.query;
493
567
  const limit = inputData.limit || 10;
494
- const offset =inputData.offset? ( inputData.offset - 1 ) * inputData.limit : 0;
568
+ const offset = inputData.offset ?
569
+ ( inputData.offset - 1 ) * inputData.limit :
570
+ 0;
495
571
  const dateRange = await getUTC( new Date(), new Date() );
496
572
 
497
573
  const temp = [];
@@ -512,7 +588,7 @@ export async function workSpace( req, res ) {
512
588
  },
513
589
  ];
514
590
 
515
- if ( inputData.searchValue&& inputData.searchValue!== '' ) {
591
+ if ( inputData.searchValue && inputData.searchValue !== '' ) {
516
592
  clientQuery.push( {
517
593
  $match: {
518
594
  $or: [
@@ -547,7 +623,6 @@ export async function workSpace( req, res ) {
547
623
  totalFilesCount: { $last: '$totalFilesCount' },
548
624
  clientName: { $last: '$clientName' },
549
625
  queueName: { $last: '$queueName' },
550
-
551
626
  },
552
627
  },
553
628
  {
@@ -584,7 +659,6 @@ export async function workSpace( req, res ) {
584
659
  _id: { clientId: '$clientId', storeId: '$storeId' },
585
660
  clientId: { $first: '$clientId' },
586
661
  completedCount: { $sum: '$completed' },
587
-
588
662
  },
589
663
  },
590
664
  {
@@ -610,7 +684,11 @@ export async function workSpace( req, res ) {
610
684
  $project: {
611
685
  clientId: 1,
612
686
  pending: {
613
- $cond: [ { $or: [ { $in: [ '$auditStatus', [ 'inprogress', 'drafted' ] ] } ] }, 1, 0 ],
687
+ $cond: [
688
+ { $or: [ { $in: [ '$auditStatus', [ 'inprogress', 'drafted' ] ] } ] },
689
+ 1,
690
+ 0,
691
+ ],
614
692
  },
615
693
  },
616
694
  },
@@ -620,7 +698,6 @@ export async function workSpace( req, res ) {
620
698
  clientId: { $first: '$clientId' },
621
699
  pendingCount: { $sum: '$pending' },
622
700
  totalCount: { $sum: 1 },
623
-
624
701
  },
625
702
  },
626
703
  {
@@ -631,7 +708,6 @@ export async function workSpace( req, res ) {
631
708
  totalCount: { $first: '$totalCount' },
632
709
  },
633
710
  },
634
-
635
711
  ];
636
712
 
637
713
  const draftedFiles = [
@@ -682,7 +758,6 @@ export async function workSpace( req, res ) {
682
758
  { clientId: { $in: clientList } },
683
759
  ],
684
760
  },
685
-
686
761
  },
687
762
  {
688
763
  $group: {
@@ -703,13 +778,8 @@ export async function workSpace( req, res ) {
703
778
  const clientAssign = [
704
779
  {
705
780
  $match: {
706
- $and: [
707
-
708
- { isCompleted: false },
709
- { clientId: { $in: clientList } },
710
- ],
781
+ $and: [ { isCompleted: false }, { clientId: { $in: clientList } } ],
711
782
  },
712
-
713
783
  },
714
784
  {
715
785
  $group: {
@@ -734,9 +804,21 @@ export async function workSpace( req, res ) {
734
804
 
735
805
  const clientAssignresult = await aggregateAssignAudit( clientAssign );
736
806
  const userAsignCount = await aggregateAssignAudit( userAsign );
737
- const mergeAll = _.merge( _.keyBy( clientDetails, 'clientId' ), _.keyBy( auditCount, 'clientId' ), _.keyBy( draftedCount, 'clientId' ), _.keyBy( clientAssignresult, 'clientId' ) );
807
+ const mergeAll = _.merge(
808
+ _.keyBy( clientDetails, 'clientId' ),
809
+ _.keyBy( auditCount, 'clientId' ),
810
+ _.keyBy( draftedCount, 'clientId' ),
811
+ _.keyBy( clientAssignresult, 'clientId' ),
812
+ );
738
813
  const finalResult = _.values( mergeAll );
739
- const merge = _.values( _.merge( _.keyBy( finalResult, 'clientId' ), _.keyBy( auditDetails, 'clientId' ), _.keyBy( userAsignCount, 'clientId' ), _.keyBy( CompletedCount, 'clientId' ) ) );
814
+ const merge = _.values(
815
+ _.merge(
816
+ _.keyBy( finalResult, 'clientId' ),
817
+ _.keyBy( auditDetails, 'clientId' ),
818
+ _.keyBy( userAsignCount, 'clientId' ),
819
+ _.keyBy( CompletedCount, 'clientId' ),
820
+ ),
821
+ );
740
822
  logger.info( { merge: merge } );
741
823
  let totalStores = 0;
742
824
  for ( let i = 0; i < merge.length; i++ ) {
@@ -748,16 +830,42 @@ export async function workSpace( req, res ) {
748
830
  temp.push( {
749
831
  clientId: merge[i].clientId,
750
832
  clientName: merge[i].clientName,
751
- completedCount: merge[i].completedCount ? Number( merge[i].completedCount ) : 0,
833
+ completedCount: merge[i].completedCount ?
834
+ Number( merge[i].completedCount ) :
835
+ 0,
752
836
  pendingByQueue: Number( pending ),
753
- pendingByUser: ( merge[i].pendingCount >= 0 ) ? Number( merge[i].pendingCount )+( merge[i].ClientAsignedCount ? Number( merge[i].ClientAsignedCount ) : 0 ) : 0,
837
+ pendingByUser:
838
+ merge[i].pendingCount >= 0 ?
839
+ Number( merge[i].pendingCount ) +
840
+ ( merge[i].ClientAsignedCount ?
841
+ Number( merge[i].ClientAsignedCount ) :
842
+ 0 ) :
843
+ 0,
754
844
  totalCount: merge[i].totalFilesCount,
755
845
  queueName: merge[i].queueName,
756
846
  isDraft: merge[i].isDrafted ? merge[i].isDrafted : false,
757
- isEnable: Number( pending ) > 0 || merge[i].isDrafted || ( merge[i].asignedCount && merge[i].asignedCount > 0 ) || ( merge[i].inprogressCount && merge[i].inprogressCount > 0 ) ? true : false,
758
- completedRatio: merge[i].totalFilesCount ? merge[i].completedCount ? Math.round( ( Number( merge[i].completedCount ) / Number( merge[i].totalFilesCount ) ) * 100 ) : 0 : 0,
759
- isAssigned: merge[i].asignedCount && merge[i].asignedCount > 0 ? true : false,
760
- Assignedcount: merge[i].asignedCount && merge[i].asignedCount > 0 ? merge[i].asignedCount : 0,
847
+ isEnable:
848
+ Number( pending ) > 0 ||
849
+ merge[i].isDrafted ||
850
+ ( merge[i].asignedCount && merge[i].asignedCount > 0 ) ||
851
+ ( merge[i].inprogressCount && merge[i].inprogressCount > 0 ) ?
852
+ true :
853
+ false,
854
+ completedRatio: merge[i].totalFilesCount ?
855
+ merge[i].completedCount ?
856
+ Math.round(
857
+ ( Number( merge[i].completedCount ) /
858
+ Number( merge[i].totalFilesCount ) ) *
859
+ 100,
860
+ ) :
861
+ 0 :
862
+ 0,
863
+ isAssigned:
864
+ merge[i].asignedCount && merge[i].asignedCount > 0 ? true : false,
865
+ Assignedcount:
866
+ merge[i].asignedCount && merge[i].asignedCount > 0 ?
867
+ merge[i].asignedCount :
868
+ 0,
761
869
  } );
762
870
  }
763
871
  }
@@ -779,7 +887,11 @@ export async function workSpace( req, res ) {
779
887
  await download( exportdata, res );
780
888
  return;
781
889
  } else {
782
- return res.sendSuccess( { result: temp, count: count.length, totalStores: totalStores } );
890
+ return res.sendSuccess( {
891
+ result: temp,
892
+ count: count.length,
893
+ totalStores: totalStores,
894
+ } );
783
895
  }
784
896
  } catch ( error ) {
785
897
  const err = error.message || 'Internal Server Error';
@@ -804,16 +916,16 @@ export async function saveDraft( req, res ) {
804
916
  const userQuery = {
805
917
  _id: inputData.auditId,
806
918
  };
807
- let userRecord ={
919
+ let userRecord = {
808
920
  isDraft: true,
809
921
  auditStatus: 'drafted',
810
922
  };
811
- const storeQuery ={
923
+ const storeQuery = {
812
924
  storeId: inputData.storeId,
813
925
  fileDate: inputData.fileDate,
814
926
  };
815
927
 
816
- let storeRecord ={
928
+ let storeRecord = {
817
929
  status: 'drafted',
818
930
  };
819
931
 
@@ -823,7 +935,7 @@ export async function saveDraft( req, res ) {
823
935
  const isoDateTime = dayjs( isoDate );
824
936
  const timeDifferenceInMinutes = currentTime.diff( isoDateTime, 'seconds' );
825
937
 
826
- userRecord.timeSpent=timeDifferenceInMinutes;
938
+ userRecord.timeSpent = timeDifferenceInMinutes;
827
939
 
828
940
  storeRecord.timeSpent = timeDifferenceInMinutes;
829
941
  }
@@ -849,7 +961,9 @@ export async function saveDraft( req, res ) {
849
961
  await createAuditLog( inputData );
850
962
  await updateOneUserAudit( userQuery, userRecord );
851
963
  await updateOneStoreAudit( storeQuery, storeRecord );
852
- return res.sendSuccess( { result: 'The file has been drafted successfully' } );
964
+ return res.sendSuccess( {
965
+ result: 'The file has been drafted successfully',
966
+ } );
853
967
  } catch ( error ) {
854
968
  const err = error.message || 'Internal Server Error';
855
969
  logger.error( { error: error, message: req.body, function: 'saveDraft' } );
@@ -861,21 +975,24 @@ export async function getDraftedData( req, res ) {
861
975
  try {
862
976
  const inputData = req.query;
863
977
  const userId = inputData.userId || req.user._id;
864
- const query={
978
+ const query = {
865
979
  fileDate: inputData.fileDate,
866
980
  storeId: inputData.storeId,
867
981
  userId: userId,
868
-
869
982
  };
870
983
  const result = await findOneAuditLog( query, {}, { createdAt: -1 }, 1 );
871
984
 
872
- if ( result.length ==0 ) {
985
+ if ( result.length == 0 ) {
873
986
  return res.sendError( 'No Data Found', 500 );
874
987
  }
875
988
  return res.sendSuccess( { result: result } );
876
989
  } catch ( error ) {
877
990
  const err = error.message || 'Internal Server Error';
878
- logger.error( { error: error, message: req.query, function: 'getDraftedData' } );
991
+ logger.error( {
992
+ error: error,
993
+ message: req.query,
994
+ function: 'getDraftedData',
995
+ } );
879
996
  return res.sendError( err, 500 );
880
997
  }
881
998
  }
@@ -883,9 +1000,11 @@ export async function getDraftedData( req, res ) {
883
1000
  export async function save( req, res ) {
884
1001
  try {
885
1002
  const bucket = JSON.parse( process.env.BUCKET );
1003
+ const sqs = JSON.parse( process.env.SQS );
1004
+
886
1005
  const inputData = req.body;
887
1006
  const params = {
888
- Key: `${inputData.storeId}/${inputData.fileDate}/${ bucket.masterJsonFile}`,
1007
+ Key: `${inputData.storeId}/${inputData.fileDate}/${bucket.masterJsonFile}`,
889
1008
  };
890
1009
 
891
1010
  if ( inputData.auditType === 'ReAudit' ) {
@@ -893,10 +1012,17 @@ export async function save( req, res ) {
893
1012
  } else {
894
1013
  params.Bucket = bucket.masterJson;
895
1014
  }
896
- logger.info( { params: params } );
897
1015
  const fileData = await getJsonFileData( params );
1016
+
1017
+ if ( fileData?.statusCode ) {
1018
+ logger.error( {
1019
+ error: `ERROR IN UPLOAD PATH: ${inputData.storeId}/${inputData.fileDate}/${bucket.masterJsonFile}`,
1020
+ type: 'UPLOAD_ERROR',
1021
+ } );
1022
+ return res.sendError( fileData, 500 );
1023
+ }
1024
+
898
1025
  const masterJsonData = JSON.parse( fileData.toString( 'utf-8' ) );
899
- logger.info( { masterJsonData: masterJsonData, length: masterJsonData.person_data.length } );
900
1026
 
901
1027
  const [ G20000, B20000, E0 ] = await Promise.all( [
902
1028
  splitG20000( masterJsonData.person_data ),
@@ -916,19 +1042,128 @@ export async function save( req, res ) {
916
1042
 
917
1043
  const uploadDataParams = {
918
1044
  Bucket: bucket.auditUploadBucket,
919
- Key: `${inputData.storeId}/${inputData.fileDate}/${bucket.masterJsonFile}`,
1045
+ Key: `${inputData.storeId}/${inputData.fileDate}/`,
920
1046
  ContentType: 'application/json',
921
- Body: JSON.stringify( tempObject ),
1047
+ fileName: `${bucket.masterJsonFile}`,
1048
+ body: JSON.stringify( tempObject ),
922
1049
  };
923
- logger.info( { uploadDataParams: uploadDataParams } );
924
1050
  const mappingUpload = await fileUpload( uploadDataParams );
925
- logger.info( { mappingUpload: mappingUpload } );
926
- return res.sendSuccess( { result: mappingUpload } );
1051
+
1052
+ if ( mappingUpload?.statusCode ) {
1053
+ logger.error( {
1054
+ error: `ERROR IN UPLOAD PATH: ${inputData.storeId}/${inputData.fileDate}/${bucket.masterJsonFile}`,
1055
+ type: 'UPLOAD_ERROR',
1056
+ } );
1057
+ return res.sendError( mappingUpload, 500 );
1058
+ }
1059
+
1060
+ let getUserAuditData = await findOneUserAudit( {
1061
+ _id: new mongoose.Types.ObjectId( inputData.auditId ),
1062
+ } );
1063
+ const isoDate = getUserAuditData.startTime;
1064
+ const currentTime = dayjs();
1065
+ const isoDateTime = dayjs( isoDate );
1066
+ const timeDifferenceInMinutes = currentTime.diff( isoDateTime, 'seconds' );
1067
+
1068
+ await updateOneUserAudit(
1069
+ { _id: new mongoose.Types.ObjectId( inputData.auditId ) },
1070
+ {
1071
+ auditStatus: 'completed',
1072
+ endTime: Date.now(),
1073
+ isDraft: false,
1074
+ afterCount: inputData.customerCount,
1075
+ timeSpent: timeDifferenceInMinutes,
1076
+ },
1077
+ );
1078
+
1079
+ /** *
1080
+ *
1081
+ * logs need to be added
1082
+ *
1083
+ *
1084
+ */
1085
+
1086
+ let storeConfig = await findOneStore(
1087
+ {
1088
+ storeId: getUserAuditData.storeId,
1089
+ },
1090
+ {
1091
+ auditConfigs: 1,
1092
+ clientId: 1,
1093
+ },
1094
+ );
1095
+ let storeAuditData = await findOneStoreAudit( {
1096
+ storeId: inputData.storeId,
1097
+ fileDate: inputData.fileDate,
1098
+ } );
1099
+
1100
+ let clientData = await findClient( { clientId: storeConfig.clientId } );
1101
+
1102
+ if ( (
1103
+ ( storeAuditData.beforeCount - inputData.customerCount ) /
1104
+ storeAuditData.beforeCount <
1105
+ storeConfig.auditConfigs.ratio
1106
+ ) && inputData.auditType == 'Audit' ) {
1107
+ logger.info(
1108
+ `Hit in Reaudit pushing queue Store Id=${inputData.storeId},File Date=${inputData.fileDate}, /n \nQueue Name = ${clientData[0].auditConfigs.queueName}`,
1109
+ 'Reaudit',
1110
+ );
1111
+
1112
+ const sqsProduceQueue = {
1113
+ QueueUrl: `${sqs.url}${clientData[0].auditConfigs.queueName}`,
1114
+ MessageBody: JSON.stringify( {
1115
+ store_id: inputData.storeId,
1116
+ audit_type: 'ReAudit',
1117
+ curr_date: inputData.fileDate,
1118
+ total_count: inputData.customerCount,
1119
+ before_count: storeAuditData.beforeCount,
1120
+ } ),
1121
+ };
1122
+ const sqsQueue = await sendMessageToQueue( sqsProduceQueue.QueueUrl, sqsProduceQueue.MessageBody );
1123
+ logger.info( { sqsQueue: sqsQueue } );
1124
+
1125
+ if ( sqsQueue.statusCode ) {
1126
+ logger.error( {
1127
+ error: `ERROR IN UPLOAD PATH: ${inputData.storeId}/${inputData.fileDate}/${bucket.masterJsonFile}`,
1128
+ type: 'UPLOAD_ERROR',
1129
+ } );
1130
+ return res.sendError( mappingUpload, 500 );
1131
+ }
1132
+
1133
+ await updateOneStoreAudit( { storeId: inputData.storeId },
1134
+ {
1135
+ status: 'not_assign',
1136
+ afterCount: inputData.customerCount,
1137
+ auditType: 'ReAudit',
1138
+ timeSpent: timeDifferenceInMinutes,
1139
+ } );
1140
+ } else {
1141
+ logger.info( 'Hit in Features', { data: ( _.omit( inputData, [ 'junk', 'employee', 'customer' ] ) ) } );
1142
+ await updateOneStoreAudit( { storeId: inputData.storeId },
1143
+ {
1144
+ status: 'completed',
1145
+ afterCount: inputData.customerCount,
1146
+ timeSpent: timeDifferenceInMinutes,
1147
+ } );
1148
+
1149
+ const sqsProduceQueue = {
1150
+ QueueUrl: `${sqs.url}${sqs.feature}`,
1151
+
1152
+ MessageBody: JSON.stringify( {
1153
+ store_id: inputData.storeId,
1154
+ store_date: inputData.fileDate,
1155
+ bucket_name: `${bucket.auditUploadBucket}`,
1156
+ } ),
1157
+ };
1158
+ logger.info( { sqsProduceQueue: sqsProduceQueue } );
1159
+ const sqsQueue = await sendMessageToQueue( sqsProduceQueue.QueueUrl, sqsProduceQueue.MessageBody );
1160
+ logger.info( { sqsQueue: sqsQueue } );
1161
+ }
1162
+
1163
+ return res.sendSuccess( { result: 'Updated Successfully' } );
927
1164
  } catch ( error ) {
928
- const err= error.message || 'Internal Server Error';
1165
+ const err = error.message || 'Internal Server Error';
929
1166
  logger.error( { error: error, message: req.body, function: 'save' } );
930
1167
  return res.sendError( err );
931
1168
  }
932
1169
  }
933
-
934
-
@@ -63,7 +63,6 @@ export const saveSchema = joi.object(
63
63
  employee: joi.array().required(),
64
64
  customerCount: joi.number().required(),
65
65
  customer: joi.array().required(),
66
- queueName: joi.string().required(),
67
66
  },
68
67
  );
69
68
 
@@ -11,3 +11,7 @@ export function createStoreAudit( record ) {
11
11
  export function aggregateStoreAudit( query ) {
12
12
  return storeAuditModel.aggregate( query, { collation: { locale: 'en', strength: 2 } } );
13
13
  }
14
+
15
+ export function findOneStoreAudit( query, fields ) {
16
+ return storeAuditModel.findOne( query, fields );
17
+ }
@@ -1,4 +1,4 @@
1
- import { checkFileExist, getQueueUrl, logger } from 'tango-app-api-middleware';
1
+ import { checkFileExist, chunkArray, getQueueUrl, logger } from 'tango-app-api-middleware';
2
2
  import { findOneUserAudit } from '../service/userAudit.service.js';
3
3
 
4
4
  export async function isExistsQueue( req, res, next ) {