tango-app-api-store-builder 1.0.0-beta-112 → 1.0.0-beta-113

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.
@@ -7,7 +7,6 @@ import * as planoService from '../service/planogram.service.js';
7
7
  import * as storeFixtureService from '../service/storeFixture.service.js';
8
8
  import * as fixtureShelfService from '../service/fixtureShelf.service.js';
9
9
  import * as planoProductService from '../service/planoProduct.service.js';
10
- import * as planoVmService from '../service/planoVm.service.js';
11
10
  import * as planoMappingService from '../service/planoMapping.service.js';
12
11
  import * as planoTaskService from '../service/planoTask.service.js';
13
12
  import * as processedTaskService from '../service/processedTaskservice.js';
@@ -15,11 +14,11 @@ import * as processedTaskService from '../service/processedTaskservice.js';
15
14
  // import * as planoTaskComplianceService from '../service/planoTask.service.js';
16
15
  // import * as planoQrConversionRequestService from '../service/planoQrConversionRequest.service.js';
17
16
  import * as fixtureConfigService from '../service/fixtureConfig.service.js';
18
- import * as fixtureLibraryService from '../service/planoLibrary.service.js';
19
17
  import mongoose from 'mongoose';
20
18
  import JSZip from 'jszip';
21
19
  import { signedUrl } from 'tango-app-api-middleware';
22
20
  import fs from 'fs';
21
+ import https from 'https';
23
22
  import os from 'os';
24
23
  import { fileURLToPath } from 'url';
25
24
  import path from 'path';
@@ -1136,7 +1135,7 @@ export async function updateFixturesShelves( req, res ) {
1136
1135
 
1137
1136
  const createdFixture = await storeFixtureService.findOneAndUpdate2( { storeName: layoutDoc.storeName, fixtureNumber: fixture?.['fixtureNumber'] }, { fixtureCode: fixture?.['Fixture ID'] } );
1138
1137
 
1139
- console.log( 'Fixture Data', fixtureData );
1138
+ // console.log( 'Fixture Data', fixtureData );
1140
1139
 
1141
1140
 
1142
1141
  const vms = typeof fixture?.['VM Template ID'] === 'string' ? fixture?.['VM Template ID']?.split( ', ' ).map( ( item ) => item.trim() ) : [];
@@ -1252,7 +1251,7 @@ export async function updateFixturesShelves( req, res ) {
1252
1251
 
1253
1252
  const createdFixture = await storeFixtureService.findOneAndUpdate2( { storeName: layoutDoc.storeName, fixtureNumber: fixture?.['fixtureNumber'] }, { fixtureCode: fixture?.['Fixture ID'] } );
1254
1253
 
1255
- console.log( 'Fixture Data', fixtureData );
1254
+ // console.log( 'Fixture Data', fixtureData );
1256
1255
 
1257
1256
  const vms = typeof fixture?.['VM Template ID'] === 'string' ? fixture?.['VM Template ID']?.split( ', ' ).map( ( item ) => item.trim() ) : [];
1258
1257
 
@@ -1301,7 +1300,7 @@ export async function updateFixturesShelves( req, res ) {
1301
1300
 
1302
1301
  const createdShelf = await fixtureShelfService.create( shelfData );
1303
1302
 
1304
- console.log( 'Shelf Data:', createdShelf );
1303
+ // console.log( 'Shelf Data:', createdShelf );
1305
1304
 
1306
1305
  shelfIndex++;
1307
1306
  }
@@ -1363,7 +1362,7 @@ export async function updateFixturesShelves( req, res ) {
1363
1362
 
1364
1363
  const createdFixture = await storeFixtureService.findOneAndUpdate2( { storeName: layoutDoc.storeName, fixtureNumber: fixture?.['fixtureNumber'] }, { fixtureCode: fixture?.['Fixture ID'] } );
1365
1364
 
1366
- console.log( 'Fixture Data', fixtureData );
1365
+ // console.log( 'Fixture Data', fixtureData );
1367
1366
 
1368
1367
  const vms = typeof fixture?.['VM Template ID'] === 'string' ? fixture?.['VM Template ID']?.split( ', ' ).map( ( item ) => item.trim() ) : [];
1369
1368
 
@@ -1488,7 +1487,7 @@ export async function updateFixturesShelves( req, res ) {
1488
1487
  };
1489
1488
 
1490
1489
  const createdFixture = await storeFixtureService.findOneAndUpdate2( { storeName: layoutDoc.storeName, fixtureNumber: fixture?.['fixtureNumber'] }, { fixtureCode: fixture?.['Fixture ID'] } );
1491
- console.log( 'Fixture Data', fixtureData );
1490
+ // console.log( 'Fixture Data', fixtureData );
1492
1491
 
1493
1492
  const vms = typeof fixture?.['VM Template ID'] === 'string' ? fixture?.['VM Template ID']?.split( ', ' ).map( ( item ) => item.trim() ) : [];
1494
1493
 
@@ -1701,7 +1700,6 @@ export async function updateInventory( req, res ) {
1701
1700
  console.log( updateData );
1702
1701
 
1703
1702
  const product = await planoProductService.create( updateData );
1704
- console.log( product );
1705
1703
  }
1706
1704
 
1707
1705
 
@@ -1826,7 +1824,6 @@ export async function updatelayoutFeedback( req, res ) {
1826
1824
  const layoutDoc = layoutFeedbacks[i].toObject();
1827
1825
 
1828
1826
  const [ q1, q2, q3 ] = layoutDoc.answers;
1829
- console.log( q3 );
1830
1827
 
1831
1828
  if ( q1.value === false ) {
1832
1829
  const floor = await storeBuilderService.findOne( { _id: layoutDoc.floorId } );
@@ -2139,7 +2136,6 @@ export async function updateFixtureFeedback( req, res ) {
2139
2136
  const vmTask = vmTaskList[j].toObject();
2140
2137
 
2141
2138
  const [ q1, q2 ] = vmTask.answers;
2142
- console.log( q2 );
2143
2139
 
2144
2140
  if ( q1.value ) continue;
2145
2141
 
@@ -2320,76 +2316,76 @@ export async function updateVmData( req, res ) {
2320
2316
  }
2321
2317
  }
2322
2318
 
2323
- // import https from 'https';
2324
- // async function scrapeCrest() {
2325
- // const storeIds = [ 'LKST2567' ];
2326
- // const apiUrl = 'https://api.getcrest.ai/api/ms_shelfsensei/layout/';
2327
- // const bearerToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ5MTEyNDYxLCJpYXQiOjE3NDkxMDg4NjEsImp0aSI6ImYzMDhmN2M3YzBlYjQ4NWU5YjVmNTJjZjRjNTkxNTM2IiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.zXRf9dgtrIhjnUJSKyLqbB8FRnTT0a-hOBos0gvKsJY';
2328
- // const filePath = 'response.json';
2329
- // let allResults = [];
2330
-
2331
- // if ( fs.existsSync( filePath ) ) {
2332
- // try {
2333
- // const existingData = fs.readFileSync( filePath, 'utf8' );
2334
- // allResults = JSON.parse( existingData );
2335
- // if ( !Array.isArray( allResults ) ) {
2336
- // allResults = [];
2337
- // }
2338
- // } catch ( error ) {
2339
- // console.error( 'Error reading existing JSON file:', error.message );
2340
- // allResults = [];
2341
- // }
2342
- // }
2343
-
2344
- // for ( const storeId of storeIds ) {
2345
- // try {
2346
- // const result = await new Promise( ( resolve ) => {
2347
- // const payload = JSON.stringify( { store_id: storeId } );
2348
- // const options = {
2349
- // method: 'POST',
2350
- // headers: {
2351
- // 'Authorization': `Bearer ${bearerToken}`,
2352
- // 'Content-Type': 'application/json',
2353
- // 'Content-Length': Buffer.byteLength( payload ),
2354
- // },
2355
- // };
2356
-
2357
- // const req = https.request( apiUrl, options, ( res ) => {
2358
- // let data = '';
2359
- // res.on( 'data', ( chunk ) => {
2360
- // data += chunk;
2361
- // } );
2362
- // res.on( 'end', () => {
2363
- // try {
2364
- // const jsonData = JSON.parse( data );
2365
- // const result = { storeName: storeId, data: jsonData };
2366
- // allResults.push( result );
2367
- // fs.writeFileSync( filePath, JSON.stringify( allResults, null, 2 ) );
2368
- // console.log( 'Received Data:', result );
2369
- // resolve( result );
2370
- // } catch ( error ) {
2371
- // console.error( `Error parsing JSON for ${storeId}:`, error.message );
2372
- // resolve( { storeName: storeId, data: null } );
2373
- // }
2374
- // } );
2375
- // } );
2376
-
2377
- // req.on( 'error', ( error ) => {
2378
- // console.error( `Error fetching data for ${storeId}:`, error.message );
2379
- // resolve( { storeName: storeId, data: null } );
2380
- // } );
2381
-
2382
- // req.write( payload );
2383
- // req.end();
2384
- // } );
2385
- // } catch ( error ) {
2386
- // console.error( `Unexpected error for ${storeId}:`, error.message );
2387
- // }
2388
- // await new Promise( ( resolve ) => setTimeout( resolve, 1000 ) );
2389
- // }
2390
- // }
2391
-
2392
- // scrapeCrest();
2319
+
2320
+ async function scrapeCrest() {
2321
+ const storeIds = [ 'LKST2566' ];
2322
+ const apiUrl = 'https://api.getcrest.ai/api/ms_shelfsensei/layout/';
2323
+ const bearerToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ5MDIyMjc4LCJpYXQiOjE3NDkwMTg2NzgsImp0aSI6ImYwZjY3OGU2NDliZTRhZGU4ZTY4MGNhMGM3YmUxOWJhIiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.eqMyUVVB4lvBLy_YXbPBLE8fbGTvTjGkrVw9Hi0HJMI';
2324
+ const filePath = 'response.json';
2325
+ let allResults = [];
2326
+
2327
+ if ( fs.existsSync( filePath ) ) {
2328
+ try {
2329
+ const existingData = fs.readFileSync( filePath, 'utf8' );
2330
+ allResults = JSON.parse( existingData );
2331
+ if ( !Array.isArray( allResults ) ) {
2332
+ allResults = [];
2333
+ }
2334
+ } catch ( error ) {
2335
+ console.error( 'Error reading existing JSON file:', error.message );
2336
+ allResults = [];
2337
+ }
2338
+ }
2339
+
2340
+ for ( const storeId of storeIds ) {
2341
+ try {
2342
+ const result = await new Promise( ( resolve ) => {
2343
+ const payload = JSON.stringify( { store_id: storeId } );
2344
+ const options = {
2345
+ method: 'POST',
2346
+ headers: {
2347
+ 'Authorization': `Bearer ${bearerToken}`,
2348
+ 'Content-Type': 'application/json',
2349
+ 'Content-Length': Buffer.byteLength( payload ),
2350
+ },
2351
+ };
2352
+
2353
+ const req = https.request( apiUrl, options, ( res ) => {
2354
+ let data = '';
2355
+ res.on( 'data', ( chunk ) => {
2356
+ data += chunk;
2357
+ } );
2358
+ res.on( 'end', () => {
2359
+ try {
2360
+ const jsonData = JSON.parse( data );
2361
+ const result = { storeName: storeId, data: jsonData };
2362
+ allResults.push( result );
2363
+ fs.writeFileSync( filePath, JSON.stringify( allResults, null, 2 ) );
2364
+ console.log( 'Received Data:', result );
2365
+ resolve( result );
2366
+ } catch ( error ) {
2367
+ console.error( `Error parsing JSON for ${storeId}:`, error.message );
2368
+ resolve( { storeName: storeId, data: null } );
2369
+ }
2370
+ } );
2371
+ } );
2372
+
2373
+ req.on( 'error', ( error ) => {
2374
+ console.error( `Error fetching data for ${storeId}:`, error.message );
2375
+ resolve( { storeName: storeId, data: null } );
2376
+ } );
2377
+
2378
+ req.write( payload );
2379
+ req.end();
2380
+ } );
2381
+ } catch ( error ) {
2382
+ console.error( `Unexpected error for ${storeId}:`, error.message );
2383
+ }
2384
+ await new Promise( ( resolve ) => setTimeout( resolve, 1000 ) );
2385
+ }
2386
+ }
2387
+
2388
+ // scrapeCrest()
2393
2389
 
2394
2390
  export async function createCrestPlanogram( req, res ) {
2395
2391
  try {
@@ -3323,248 +3319,246 @@ export async function updateCrestVms( req, res ) {
3323
3319
  }
3324
3320
 
3325
3321
 
3326
- // async function filterStores() {
3327
- // const stores = [
3328
- // 'ST338', 'LKST1304', 'ST303', 'LKST1228', 'LKST499', 'LKST479', 'ST320',
3329
- // 'LKST515', 'LKST406', 'ST392', 'ST328', 'ST332', 'LKST487', 'ST312',
3330
- // 'LKST615', 'LKST352', 'LKST457', 'LKST439', 'LKST347', 'LKST1084',
3331
- // 'LKST380', 'ST298', 'LKST356', 'LKST223', 'LKST480', 'ST30', 'ST285',
3332
- // 'LKST500', 'LKST466', 'LKST321', 'LKST678', 'LKST383', 'LKST365',
3333
- // 'LKST374', 'ST302', 'LKST420', 'LKST394', 'LKST444', 'LKST314',
3334
- // 'LKST01', 'LKST357', 'LKST465', 'LKST331', 'LKST440', 'LKST345',
3335
- // 'LKST389', 'ST330', 'LKST299', 'ST244', 'LKST294', 'ST314', 'LKST361',
3336
- // 'LKST377', 'LKST390', 'ST335', 'LKST416', 'ST293', 'LKST341', 'LKST501',
3337
- // 'LKST408', 'LKST227', 'LKST353', 'LKST364', 'ST318', 'LKST326',
3338
- // 'LKST344', 'ST321', 'LKST384', 'LKST496', 'LKST427', 'LKST325',
3339
- // 'LKST282', 'ST197', 'LKST388', 'LKST338', 'LKST371', 'ST326', 'LKST428',
3340
- // 'LKST112', 'LKST334', 'ST319', 'LKST464', 'LKST490', 'LKST11',
3341
- // 'LKST502', 'LKST1438',
3342
- // ];
3322
+ async function filterStores() {
3323
+ const stores = [
3324
+ 'ST338', 'LKST1304', 'ST303', 'LKST1228', 'LKST499', 'LKST479', 'ST320',
3325
+ 'LKST515', 'LKST406', 'ST392', 'ST328', 'ST332', 'LKST487', 'ST312',
3326
+ 'LKST615', 'LKST352', 'LKST457', 'LKST439', 'LKST347', 'LKST1084',
3327
+ 'LKST380', 'ST298', 'LKST356', 'LKST223', 'LKST480', 'ST30', 'ST285',
3328
+ 'LKST500', 'LKST466', 'LKST321', 'LKST678', 'LKST383', 'LKST365',
3329
+ 'LKST374', 'ST302', 'LKST420', 'LKST394', 'LKST444', 'LKST314',
3330
+ 'LKST01', 'LKST357', 'LKST465', 'LKST331', 'LKST440', 'LKST345',
3331
+ 'LKST389', 'ST330', 'LKST299', 'ST244', 'LKST294', 'ST314', 'LKST361',
3332
+ 'LKST377', 'LKST390', 'ST335', 'LKST416', 'ST293', 'LKST341', 'LKST501',
3333
+ 'LKST408', 'LKST227', 'LKST353', 'LKST364', 'ST318', 'LKST326',
3334
+ 'LKST344', 'ST321', 'LKST384', 'LKST496', 'LKST427', 'LKST325',
3335
+ 'LKST282', 'ST197', 'LKST388', 'LKST338', 'LKST371', 'ST326', 'LKST428',
3336
+ 'LKST112', 'LKST334', 'ST319', 'LKST464', 'LKST490', 'LKST11',
3337
+ 'LKST502', 'LKST1438',
3338
+ ];
3339
+
3340
+ const rawData = fs.readFileSync( 'crest_scrap_v1.json', 'utf8' );
3341
+ const allStores = JSON.parse( rawData );
3342
+
3343
+ const filteredStores = allStores.filter( ( store ) => stores.includes( store.storeName ) );
3344
+
3345
+ fs.writeFileSync( 'crest_filtered.json', JSON.stringify( filteredStores, null, 2 ) );
3346
+ }
3347
+
3348
+ import fsp from 'fs/promises';
3343
3349
 
3344
- // const rawData = fs.readFileSync( 'crest_scrap_v1.json', 'utf8' );
3345
- // const allStores = JSON.parse( rawData );
3350
+ import sharp from 'sharp';
3346
3351
 
3347
- // const filteredStores = allStores.filter( ( store ) => stores.includes( store.storeName ) );
3348
3352
 
3349
- // fs.writeFileSync( 'crest_filtered.json', JSON.stringify( filteredStores, null, 2 ) );
3350
- // }
3353
+ const stitchImagesFromZips = async () => {
3354
+ const zip1Path = 'crest_plano.zip';
3355
+ const zip2Path = 'tango_plano.zip';
3356
+ const outputDir = 'stitched';
3351
3357
 
3352
- // import fsp from 'fs/promises';
3358
+ const loadZip = async ( zipPath ) => {
3359
+ const buffer = await fsp.readFile( zipPath );
3360
+ return await JSZip.loadAsync( buffer );
3361
+ };
3353
3362
 
3354
- import sharp from 'sharp';
3363
+ const extractImages = async ( zip ) => {
3364
+ const imageFiles = {};
3365
+ const imageRegex = /\.(png|jpe?g)$/i;
3366
+
3367
+ for ( const [ name, file ] of Object.entries( zip.files ) ) {
3368
+ const base = path.basename( name );
3369
+ if ( !file.dir && imageRegex.test( base ) ) {
3370
+ imageFiles[base] = await file.async( 'nodebuffer' );
3371
+ }
3372
+ }
3373
+
3374
+ return imageFiles;
3375
+ };
3376
+
3377
+ const stitchOrCenter = async ( buffer1, buffer2, outputPath ) => {
3378
+ const totalWidth = 7000;
3379
+ const width1 = Math.round( totalWidth * 0.3 );
3380
+ const width2 = Math.round( totalWidth * 0.7 );
3381
+
3382
+ let img1 = buffer1 ? await sharp( buffer1 ).resize( { width: width1 } ).toBuffer() : null;
3383
+ let img2 = buffer2 ? await sharp( buffer2 ).resize( { width: width2 } ).toBuffer() : null;
3384
+
3385
+ const [ meta1, meta2 ] = await Promise.all( [
3386
+ img1 ? sharp( img1 ).metadata() : Promise.resolve( { height: 0 } ),
3387
+ img2 ? sharp( img2 ).metadata() : Promise.resolve( { height: 0 } ),
3388
+ ] );
3389
+
3390
+ const maxHeight = Math.max( meta1.height, meta2.height );
3391
+
3392
+ const composites = [];
3393
+ if ( img1 ) composites.push( { input: img1, top: 0, left: 0 } );
3394
+ if ( img2 ) composites.push( { input: img2, top: 0, left: width1 } );
3395
+
3396
+ await sharp( {
3397
+ create: {
3398
+ width: totalWidth,
3399
+ height: maxHeight,
3400
+ channels: 4,
3401
+ background: { r: 255, g: 255, b: 255, alpha: 0 },
3402
+ },
3403
+ } )
3404
+ .composite( composites )
3405
+ .png()
3406
+ .toFile( outputPath );
3407
+ };
3408
+
3409
+ try {
3410
+ await fsp.mkdir( outputDir, { recursive: true } );
3411
+
3412
+ const [ zip1, zip2 ] = await Promise.all( [ loadZip( zip1Path ), loadZip( zip2Path ) ] );
3413
+ const [ images1, images2 ] = await Promise.all( [ extractImages( zip1 ), extractImages( zip2 ) ] );
3355
3414
 
3415
+ const allFilenames = new Set( [ ...Object.keys( images1 ), ...Object.keys( images2 ) ] );
3356
3416
 
3357
- // const stitchImagesFromZips = async () => {
3358
- // const zip1Path = 'crest_plano.zip';
3359
- // const zip2Path = 'tango_plano.zip';
3360
- // const outputDir = 'stitched';
3361
-
3362
- // const loadZip = async ( zipPath ) => {
3363
- // const buffer = await fsp.readFile( zipPath );
3364
- // return await JSZip.loadAsync( buffer );
3365
- // };
3366
-
3367
- // const extractImages = async ( zip ) => {
3368
- // const imageFiles = {};
3369
- // const imageRegex = /\.(png|jpe?g)$/i;
3370
-
3371
- // for ( const [ name, file ] of Object.entries( zip.files ) ) {
3372
- // const base = path.basename( name );
3373
- // if ( !file.dir && imageRegex.test( base ) ) {
3374
- // imageFiles[base] = await file.async( 'nodebuffer' );
3375
- // }
3376
- // }
3377
-
3378
- // return imageFiles;
3379
- // };
3380
-
3381
- // const stitchOrCenter = async ( buffer1, buffer2, outputPath ) => {
3382
- // const totalWidth = 7000;
3383
- // const width1 = Math.round( totalWidth * 0.3 );
3384
- // const width2 = Math.round( totalWidth * 0.7 );
3385
-
3386
- // let img1 = buffer1 ? await sharp( buffer1 ).resize( { width: width1 } ).toBuffer() : null;
3387
- // let img2 = buffer2 ? await sharp( buffer2 ).resize( { width: width2 } ).toBuffer() : null;
3388
-
3389
- // const [ meta1, meta2 ] = await Promise.all( [
3390
- // img1 ? sharp( img1 ).metadata() : Promise.resolve( { height: 0 } ),
3391
- // img2 ? sharp( img2 ).metadata() : Promise.resolve( { height: 0 } ),
3392
- // ] );
3393
-
3394
- // const maxHeight = Math.max( meta1.height, meta2.height );
3395
-
3396
- // const composites = [];
3397
- // if ( img1 ) composites.push( { input: img1, top: 0, left: 0 } );
3398
- // if ( img2 ) composites.push( { input: img2, top: 0, left: width1 } );
3399
-
3400
- // await sharp( {
3401
- // create: {
3402
- // width: totalWidth,
3403
- // height: maxHeight,
3404
- // channels: 4,
3405
- // background: { r: 255, g: 255, b: 255, alpha: 0 },
3406
- // },
3407
- // } )
3408
- // .composite( composites )
3409
- // .png()
3410
- // .toFile( outputPath );
3411
- // };
3412
-
3413
- // try {
3414
- // await fsp.mkdir( outputDir, { recursive: true } );
3415
-
3416
- // const [ zip1, zip2 ] = await Promise.all( [ loadZip( zip1Path ), loadZip( zip2Path ) ] );
3417
- // const [ images1, images2 ] = await Promise.all( [ extractImages( zip1 ), extractImages( zip2 ) ] );
3418
-
3419
- // const allFilenames = new Set( [ ...Object.keys( images1 ), ...Object.keys( images2 ) ] );
3420
-
3421
- // for ( const name of allFilenames ) {
3422
- // const buffer1 = images1[name] || null;
3423
- // const buffer2 = images2[name] || null;
3424
- // const outputPath = path.join( outputDir, `${name.replace( /\.[^/.]+$/, '' )}.png` );
3425
-
3426
- // try {
3427
- // await stitchOrCenter( buffer1, buffer2, outputPath );
3428
- // console.log( ` Processed: ${name}` );
3429
- // } catch ( err ) {
3430
- // console.error( ` Error processing ${name}:`, err.message );
3431
- // }
3432
- // }
3433
- // } catch ( err ) {
3434
- // console.error( ' Unexpected error:', err.message );
3435
- // }
3436
- // };
3417
+ for ( const name of allFilenames ) {
3418
+ const buffer1 = images1[name] || null;
3419
+ const buffer2 = images2[name] || null;
3420
+ const outputPath = path.join( outputDir, `${name.replace( /\.[^/.]+$/, '' )}.png` );
3421
+
3422
+ try {
3423
+ await stitchOrCenter( buffer1, buffer2, outputPath );
3424
+ console.log( ` Processed: ${name}` );
3425
+ } catch ( err ) {
3426
+ console.error( ` Error processing ${name}:`, err.message );
3427
+ }
3428
+ }
3429
+ } catch ( err ) {
3430
+ console.error( ' Unexpected error:', err.message );
3431
+ }
3432
+ };
3437
3433
 
3438
3434
  // stitchImagesFromZips();
3439
3435
 
3440
3436
 
3441
- import { Builder } from 'selenium-webdriver';
3442
- // import chrome from 'selenium-webdriver/chrome.js';
3437
+ import { Builder, By, until } from 'selenium-webdriver';
3438
+ import chrome from 'selenium-webdriver/chrome.js';
3443
3439
  import fetch from 'node-fetch';
3444
3440
 
3445
3441
  import fetchCookie from 'fetch-cookie';
3446
3442
 
3447
3443
 
3448
- // async function downloadCrestImages() {
3449
- // const storeList = await planoService.find( {} );
3450
- // // const storeIds = storeList.map( ( store ) => store.toObject().storeName );
3451
- // const storeIds = [ 'LKST1304' ];
3452
-
3453
-
3454
- // const invalidateUrl = 'https://app.getcrest.ai/api/ms_iam/user/session/override/';
3455
- // const tokenUrl = 'https://app.getcrest.ai/api/ms_iam/token/';
3456
-
3457
- // let authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ3NTEwNDAxLCJpYXQiOjE3NDc1MDY4MDEsImp0aSI6IjQ0YzNjOWNkZjUzYjQ5ZWE5OGQ3NWQxOTI1NGMxMGRkIiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.5OYkUq4kIWDUXothNCCfk6GIQHlhiMdOuHzuczWt6QM';
3458
-
3459
- // const fetchWithCookies = fetchCookie( fetch );
3460
-
3461
- // async function fetchNewToken() {
3462
- // const invalidate = await fetchWithCookies( invalidateUrl, {
3463
- // 'method': 'POST',
3464
- // 'headers': { 'Content-Type': 'application/json' },
3465
- // 'body': JSON.stringify( { 'email': 'tango.lenskart@getcrest.ai', 'password': 'Tangolenskart@123' } ),
3466
- // } );
3467
-
3468
- // const invalidateData = await invalidate.json();
3469
-
3470
- // console.log( invalidateData );
3471
-
3472
- // console.log( 'Fetching new token...' );
3473
- // const res = await fetchWithCookies( tokenUrl, {
3474
- // 'method': 'POST',
3475
- // 'Accept': 'application/json, text/javascript, */*; q=0.01',
3476
- // 'headers': { 'Content-Type': 'application/json' },
3477
- // 'body': JSON.stringify( { 'email': 'tango.lenskart@getcrest.ai', 'password': 'Tangolenskart@123' } ),
3478
- // } );
3479
-
3480
- // if ( !res.ok ) {
3481
- // throw new Error( `Failed to fetch token: ${res.status}` );
3482
- // }
3483
-
3484
- // const data = await res.json();
3485
- // console.log( data );
3486
- // authToken = data.access;
3487
- // return authToken;
3488
- // }
3489
-
3490
- // async function runAutomation( token, storeId, retries = 3 ) {
3491
- // let attempts = 0;
3492
-
3493
- // while ( attempts < retries ) {
3494
- // const options = new chrome.Options();
3495
- // // options.addArguments( 'headless' );
3496
- // options.addArguments( 'disable-gpu' );
3497
-
3498
- // const driver = await new Builder()
3499
- // .forBrowser( 'chrome' )
3500
- // .setChromeOptions( options )
3501
- // .build();
3502
-
3503
- // try {
3504
- // const url = `https://app.getcrest.ai/pvt/?auth=${token}&module=planno&store_id=${storeId}`;
3505
- // await driver.get( url );
3506
- // const currentUrl = await driver.getCurrentUrl();
3507
- // if ( currentUrl.includes( '/login' ) ) {
3508
- // console.warn( `Redirected to login for store ${storeId}. Retrying with new token...` );
3509
- // await driver.quit();
3510
- // const newToken = await fetchNewToken();
3511
- // return await runAutomation( newToken, storeId, retries );
3512
- // }
3513
-
3514
- // const button = await driver.wait( until.elementLocated(
3515
- // By.xpath( '//*[contains(@class, "MuiButtonBase-root") and contains(@class, "MuiButton-root") and contains(@class, "MuiButton-text") and contains(@class, "MuiButton-disableElevation") and contains(@class, "jss35") and contains(@class, "jss47") and contains(@class, "jss37") and contains(@class, "jss144")]' ),
3516
- // ), 10000 );
3517
- // await button.click();
3518
-
3519
- // const checkbox = await driver.wait(
3520
- // until.elementLocated(
3521
- // By.xpath( '//*[contains(@class, "MuiCheckbox-root") and contains(@class, "MuiIconButton-root")]//input[@type="checkbox"]' ),
3522
- // ),
3523
- // 10000,
3524
- // );
3525
- // await checkbox.click();
3526
-
3527
- // const downloadIcon = await driver.wait(
3528
- // until.elementLocated(
3529
- // By.xpath( '//button[contains(@class, "cool-tooltip")]' ),
3530
- // ),
3531
- // 10000,
3532
- // );
3533
- // await downloadIcon.click();
3534
-
3535
-
3536
- // console.log( `Download triggered for store: ${storeId}` );
3537
- // await driver.sleep( 5000 );
3538
- // return;
3539
- // } catch ( err ) {
3540
- // attempts++;
3541
- // console.error( `Error for store ${storeId}, attempt ${attempts}: ${err.message}` );
3542
- // if ( attempts >= retries ) {
3543
- // console.error( `Failed for store ${storeId} after ${retries} attempts` );
3544
- // } else {
3545
- // console.log( `Retrying for store ${storeId}, attempt ${attempts + 1}` );
3546
- // }
3547
- // } finally {
3548
- // try {
3549
- // if ( driver && ( await driver.getSession() ) ) {
3550
- // await driver.quit();
3551
- // }
3552
- // } catch ( e ) {
3553
-
3554
- // }
3555
- // }
3556
- // }
3557
- // }
3558
-
3559
- // for ( const storeId of storeIds ) {
3560
- // try {
3561
- // console.log( `Starting automation for store: ${storeId}` );
3562
- // await runAutomation( authToken, storeId );
3563
- // } catch ( error ) {
3564
- // console.error( `Automation failed for store ${storeId}: ${error.message}` );
3565
- // }
3566
- // }
3567
- // }
3444
+ async function downloadCrestImages() {
3445
+ const storeList = await planoService.find( {} );
3446
+ const storeIds = storeList.map( ( store ) => store.toObject().storeName );
3447
+
3448
+ const invalidateUrl = 'https://app.getcrest.ai/api/ms_iam/user/session/override/';
3449
+ const tokenUrl = 'https://app.getcrest.ai/api/ms_iam/token/';
3450
+
3451
+ let authToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ0NzE4MjUzLCJpYXQiOjE3NDQ3MTQ2NTMsImp0aSI6Ijk5ZTAyYjU4ODg2NjQ3MDk4Y2NlY2NmODZlYzYzYTU4IiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.7g1XS48l7mVsOcDXHLC7VFLFyJ-p13e2kkJlb8uFc_g';
3452
+
3453
+ const fetchWithCookies = fetchCookie( fetch );
3454
+
3455
+ async function fetchNewToken() {
3456
+ const invalidate = await fetchWithCookies( invalidateUrl, {
3457
+ 'method': 'POST',
3458
+ 'headers': { 'Content-Type': 'application/json' },
3459
+ 'body': JSON.stringify( { 'email': 'tango.lenskart@getcrest.ai', 'password': 'Tangolenskart@123' } ),
3460
+ } );
3461
+
3462
+ const invalidateData = await invalidate.json();
3463
+
3464
+ console.log( invalidateData );
3465
+
3466
+ console.log( 'Fetching new token...' );
3467
+ const res = await fetchWithCookies( tokenUrl, {
3468
+ 'method': 'POST',
3469
+ 'Accept': 'application/json, text/javascript, */*; q=0.01',
3470
+ 'headers': { 'Content-Type': 'application/json' },
3471
+ 'body': JSON.stringify( { 'email': 'tango.lenskart@getcrest.ai', 'password': 'Tangolenskart@123' } ),
3472
+ } );
3473
+
3474
+ if ( !res.ok ) {
3475
+ throw new Error( `Failed to fetch token: ${res.status}` );
3476
+ }
3477
+
3478
+ const data = await res.json();
3479
+ console.log( data );
3480
+ authToken = data.access;
3481
+ return authToken;
3482
+ }
3483
+
3484
+ async function runAutomation( token, storeId, retries = 3 ) {
3485
+ let attempts = 0;
3486
+
3487
+ while ( attempts < retries ) {
3488
+ const options = new chrome.Options();
3489
+ options.addArguments( 'headless' );
3490
+ options.addArguments( 'disable-gpu' );
3491
+
3492
+ const driver = await new Builder()
3493
+ .forBrowser( 'chrome' )
3494
+ .setChromeOptions( options )
3495
+ .build();
3496
+
3497
+ try {
3498
+ const url = `https://app.getcrest.ai/pvt/?auth=${token}&module=planno&store_id=${storeId}`;
3499
+ await driver.get( url );
3500
+ const currentUrl = await driver.getCurrentUrl();
3501
+ if ( currentUrl.includes( '/login' ) ) {
3502
+ console.warn( `Redirected to login for store ${storeId}. Retrying with new token...` );
3503
+ await driver.quit();
3504
+ const newToken = await fetchNewToken();
3505
+ return await runAutomation( newToken, storeId, retries );
3506
+ }
3507
+
3508
+ const button = await driver.wait( until.elementLocated(
3509
+ By.xpath( '//*[contains(@class, "MuiButtonBase-root") and contains(@class, "MuiButton-root") and contains(@class, "MuiButton-text") and contains(@class, "MuiButton-disableElevation") and contains(@class, "jss35") and contains(@class, "jss47") and contains(@class, "jss37") and contains(@class, "jss144")]' ),
3510
+ ), 10000 );
3511
+ await button.click();
3512
+
3513
+ const checkbox = await driver.wait(
3514
+ until.elementLocated(
3515
+ By.xpath( '//*[contains(@class, "MuiCheckbox-root") and contains(@class, "MuiIconButton-root")]//input[@type="checkbox"]' ),
3516
+ ),
3517
+ 10000,
3518
+ );
3519
+ await checkbox.click();
3520
+
3521
+ const downloadIcon = await driver.wait(
3522
+ until.elementLocated(
3523
+ By.xpath( '//button[contains(@class, "cool-tooltip")]' ),
3524
+ ),
3525
+ 10000,
3526
+ );
3527
+ await downloadIcon.click();
3528
+
3529
+
3530
+ console.log( `Download triggered for store: ${storeId}` );
3531
+ await driver.sleep( 5000 );
3532
+ return;
3533
+ } catch ( err ) {
3534
+ attempts++;
3535
+ console.error( `Error for store ${storeId}, attempt ${attempts}: ${err.message}` );
3536
+ if ( attempts >= retries ) {
3537
+ console.error( `Failed for store ${storeId} after ${retries} attempts` );
3538
+ } else {
3539
+ console.log( `Retrying for store ${storeId}, attempt ${attempts + 1}` );
3540
+ }
3541
+ } finally {
3542
+ try {
3543
+ if ( driver && ( await driver.getSession() ) ) {
3544
+ await driver.quit();
3545
+ }
3546
+ } catch ( e ) {
3547
+
3548
+ }
3549
+ }
3550
+ }
3551
+ }
3552
+
3553
+ for ( const storeId of storeIds ) {
3554
+ try {
3555
+ console.log( `Starting automation for store: ${storeId}` );
3556
+ await runAutomation( authToken, storeId );
3557
+ } catch ( error ) {
3558
+ console.error( `Automation failed for store ${storeId}: ${error.message}` );
3559
+ }
3560
+ }
3561
+ }
3568
3562
 
3569
3563
  // downloadCrestImages();
3570
3564
  export async function updatePlanoFixtureLayout( planoId, floorId ) {
@@ -4139,12 +4133,36 @@ export async function downloadPlanoImage( req, res ) {
4139
4133
  date_string: { $gte: req.body.fromDate, $lte: req.body.toDate },
4140
4134
  type: 'layout',
4141
4135
  status: 'incomplete',
4142
- storeName: { $in: req.body.store },
4143
4136
  },
4144
4137
  },
4138
+ {
4139
+ $lookup: {
4140
+ from: 'planograms',
4141
+ let: { plano_id: '$planoId' },
4142
+ pipeline: [
4143
+ {
4144
+ $match: {
4145
+ $expr: {
4146
+ $and: [
4147
+ { $eq: [ '$_id', '$$plano_id' ] },
4148
+ ],
4149
+ },
4150
+ },
4151
+ },
4152
+ {
4153
+ $project: {
4154
+ storeName: 1,
4155
+ _id: 0,
4156
+ },
4157
+ },
4158
+ ],
4159
+ as: 'planogram',
4160
+ },
4161
+ },
4162
+ { $unwind: { path: '$planogram', preserveNullAndEmptyArrays: true } },
4145
4163
  {
4146
4164
  $project: {
4147
- storeName: 1,
4165
+ storeName: '$planogram.storeName',
4148
4166
  answers: 1,
4149
4167
  type: 1,
4150
4168
  status: 1,
@@ -4158,18 +4176,17 @@ export async function downloadPlanoImage( req, res ) {
4158
4176
  if ( !taskDetails.length ) {
4159
4177
  return res.sendError( 'No data found', 204 );
4160
4178
  }
4161
- let planoList = [ ...new Set( taskDetails.map( ( ele ) => ele.planoId ) ) ];
4162
- console.log( planoList );
4163
- let storeList = [ ...new Set( taskDetails.map( ( ele ) => ele.storeName ) ) ];
4164
- console.log( storeList );
4179
+ let planoList = taskDetails.map( ( ele ) => ele.planoId );
4180
+ let storeList = taskDetails.map( ( ele ) => ele.storeName );
4165
4181
  async function sleep( ms ) {
4166
4182
  return new Promise( ( resolve ) => setTimeout( resolve, ms ) );
4167
4183
  }
4168
4184
 
4169
4185
  async function openPlanoUrls( planoList ) {
4170
4186
  for ( let id of planoList ) {
4171
- const url = `https://plano-builder.tangoeye.ai/#/plano?planoId=${id}&token&download=1&url=http://localhost:3008`;
4187
+ const url = `http://localhost:8080/#/plano?planoId=${id}&token&url=http://localhost:3008`;
4172
4188
  const driver = await new Builder().forBrowser( 'chrome' ).build();
4189
+
4173
4190
  try {
4174
4191
  await driver.get( url );
4175
4192
  await sleep( 20000 );
@@ -4189,7 +4206,6 @@ export async function downloadPlanoImage( req, res ) {
4189
4206
  if ( !req.body?.merge ) {
4190
4207
  const downloadsPath = path.join( os.homedir(), 'Downloads' );
4191
4208
  const targetFolder = path.join( __dirname, '..', '..', `${req.body.file}Images` );
4192
- console.log( 'test' );
4193
4209
  await openPlanoUrls( planoList );
4194
4210
  if ( !fs.existsSync( targetFolder ) ) {
4195
4211
  fs.mkdirSync( targetFolder, { recursive: true } );
@@ -5706,7 +5722,7 @@ export async function getVideoLinks( req, res ) {
5706
5722
  continue;
5707
5723
  }
5708
5724
  const [ q1, q2, q3 ] = data.answers;
5709
- console.log( q1, q2 );
5725
+
5710
5726
  const params = {
5711
5727
  Bucket: 'tango-planogram',
5712
5728
  file_path: q3?.video || null,
@@ -6999,28 +7015,28 @@ export async function updateExcelPlanogram( req, res ) {
6999
7015
  }
7000
7016
  }
7001
7017
 
7002
- // async function downloadImage() {
7003
- // const url = 'https://api.getcrest.ai/api/ms_data_preparation/master_data/attachment/?preview=0&attachment_id=2934';
7018
+ async function downloadImage() {
7019
+ const url = 'https://api.getcrest.ai/api/ms_data_preparation/master_data/attachment/?preview=0&attachment_id=2934';
7004
7020
 
7005
- // try {
7006
- // const response = await fetch( url, {
7007
- // headers: {
7008
- // Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ3MjE0MjcxLCJpYXQiOjE3NDcyMTA2NzEsImp0aSI6ImM4ZjQ4ZDY2YWJkYzRmNDU4MWI4OGE4MTMwODVjOTUwIiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.IOw_0yNA6CMBCIn7cxjPR0FqHI949WplCKzlkr8aK7g',
7009
- // Cookie: 'prod_session_key=w144dqljxlh096487nc33rm09vwtossh; prod_session_key=7mljy9k7niwpw4btbbyvuhkz7otbdh6v',
7010
- // },
7011
- // } );
7021
+ try {
7022
+ const response = await fetch( url, {
7023
+ headers: {
7024
+ Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ3MjE0MjcxLCJpYXQiOjE3NDcyMTA2NzEsImp0aSI6ImM4ZjQ4ZDY2YWJkYzRmNDU4MWI4OGE4MTMwODVjOTUwIiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.IOw_0yNA6CMBCIn7cxjPR0FqHI949WplCKzlkr8aK7g',
7025
+ Cookie: 'prod_session_key=w144dqljxlh096487nc33rm09vwtossh; prod_session_key=7mljy9k7niwpw4btbbyvuhkz7otbdh6v',
7026
+ },
7027
+ } );
7012
7028
 
7013
- // if ( !response.ok ) throw new Error( `HTTP error! Status: ${response.status}` );
7029
+ if ( !response.ok ) throw new Error( `HTTP error! Status: ${response.status}` );
7014
7030
 
7015
- // const dest = fs.createWriteStream( '2934.png' );
7016
- // response.body.pipe( dest );
7031
+ const dest = fs.createWriteStream( '2934.png' );
7032
+ response.body.pipe( dest );
7017
7033
 
7018
- // dest.on( 'finish', () => console.log( 'Image saved as image.jpg' ) );
7019
- // dest.on( 'error', ( err ) => console.error( 'File write error:', err ) );
7020
- // } catch ( err ) {
7021
- // console.error( 'Fetch error:', err );
7022
- // }
7023
- // }
7034
+ dest.on( 'finish', () => console.log( 'Image saved as image.jpg' ) );
7035
+ dest.on( 'error', ( err ) => console.error( 'File write error:', err ) );
7036
+ } catch ( err ) {
7037
+ console.error( 'Fetch error:', err );
7038
+ }
7039
+ }
7024
7040
 
7025
7041
  // downloadImage();
7026
7042
 
@@ -7067,1416 +7083,73 @@ export async function recorrectTaskData( req, res ) {
7067
7083
  }
7068
7084
 
7069
7085
 
7070
- export async function migrateCrestv1( req, res ) {
7071
- try {
7072
- if ( req?.headers?.authorization?.split( ' ' )[1] !== 'hwjXfCD6TgMvc82cuSGZ9bNv9MuXsaiQ6uvx' ) {
7073
- return res.sendError( 'Unauthorized', 401 );
7074
- }
7075
-
7076
- const startTime = Date.now();
7077
-
7078
- const layoutApiUrl = 'https://api.getcrest.ai/api/ms_shelfsensei/layout/';
7079
- let staticToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzQ1NTE3MjQxLCJpYXQiOjE3NDU1MTM2NDEsImp0aSI6Ijg3MWVlNTA3ODY2OTQ5OTVhMTQ0YTk4NzQyNzY0MzEzIiwidXNlcl9pZCI6MTA4NSwiaWQiOjEwODUsImlzX21lZXNlZWtfYWNjb3VudCI6ZmFsc2UsImN1c3RvbWVyX2dyb3VwIjozOTgsImxpY2VuY2Vfc2NvcGVzIjpbeyJyZXNvdXJjZV9zZXQiOiJwcF9zZXQiLCJzY29wZV9yb2xlIjoiY29udHJpYnV0b3IifSx7InJlc291cmNlX3NldCI6ImRwX3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9LHsicmVzb3VyY2Vfc2V0IjoiZGZfc2V0Iiwic2NvcGVfcm9sZSI6ImNvbnRyaWJ1dG9yIn0seyJyZXNvdXJjZV9zZXQiOiJkZWZhdWx0X3NldCIsInNjb3BlX3JvbGUiOiJjb250cmlidXRvciJ9XX0.eGzTMGwwstr13M0Hu1Ls5-gkE_oSPMJJBL2wgygT6Ac';
7080
- const fetchWithCookies = fetchCookie( fetch );
7081
-
7082
-
7083
- async function fetchStoreData( store, bearerToken, res ) {
7084
- const payload = JSON.stringify( { store_id: store.toObject().storeName?.toUpperCase() } );
7085
-
7086
- try {
7087
- const response = await fetch( layoutApiUrl, {
7088
- method: 'POST',
7089
- headers: {
7090
- 'Authorization': `Bearer ${bearerToken}`,
7091
- 'Content-Type': 'application/json',
7092
- 'Content-Length': Buffer.byteLength( payload ),
7093
- },
7094
- body: payload,
7095
- } );
7096
-
7097
- const data = await response.text();
7098
- let jsonData = null;
7086
+ function fillFeedbackFromJson( excelPath, jsonData, outputPath ) {
7087
+ const workbook = xlsx.readFile( excelPath );
7088
+ const sheetName = workbook.SheetNames[0];
7089
+ const sheet = workbook.Sheets[sheetName];
7099
7090
 
7100
- try {
7101
- jsonData = JSON.parse( data );
7102
- } catch ( parseError ) {
7103
- logger.error( { functionName: `Warning: Received invalid JSON for store ${store.toObject().storeName}`, error: parseError } );
7104
- console.warn( `Warning: Received invalid JSON for store ${store.toObject().storeName}` );
7105
- return { storeName: store.toObject().storeName, data: null };
7106
- }
7091
+ const data = xlsx.utils.sheet_to_json( sheet, { defval: 'Transformed by Data.Page' } );
7107
7092
 
7108
- if ( jsonData.result === 'Token is invalid or expired' ) {
7109
- console.log( 'Token expired, retrying...' );
7110
- try {
7111
- const newToken = await fetchNewToken();
7112
- staticToken = newToken;
7113
- return await fetchStoreData( store, newToken, res );
7114
- } catch ( retryError ) {
7115
- logger.error( { functionName: 'Failed to refresh token', error: retryError } );
7116
- console.log( retryError );
7117
- return res.sendError( 'Failed to refresh token', 401 );
7118
- }
7119
- }
7093
+ const feedbackMap = {};
7094
+ jsonData.forEach( ( entry ) => {
7095
+ feedbackMap[entry.store] = entry.videoUrl;
7096
+ } );
7120
7097
 
7121
- return { storeName: store.toObject().storeName, data: jsonData };
7122
- } catch ( error ) {
7123
- logger.error( { functionName: `Error fetching data for ${store.toObject().storeName}:`, error } );
7124
- console.error( `Error fetching data for ${store.toObject().storeName}:`, error.message );
7125
- return { storeName: store.toObject().storeName, data: null };
7126
- }
7098
+ const updatedData = data.map( ( row ) => {
7099
+ const store = row.storeName;
7100
+ if ( feedbackMap[store] ) {
7101
+ row.FeedBack = feedbackMap[store];
7127
7102
  }
7103
+ return row;
7104
+ } );
7128
7105
 
7106
+ const newSheet = xlsx.utils.json_to_sheet( updatedData );
7129
7107
 
7130
- const fetchNewToken = async () => {
7131
- const email = 'tango.lenskart@getcrest.ai';
7132
- const password = 'Tangolenskart@123';
7133
-
7134
- const credentials = JSON.stringify( { email, password } );
7135
-
7136
- const invalidateUrl = 'https://app.getcrest.ai/api/ms_iam/user/session/override/';
7137
- const tokenUrl = 'https://app.getcrest.ai/api/ms_iam/token/';
7138
-
7139
- try {
7140
- const invalidateRes = await fetchWithCookies( invalidateUrl, {
7141
- method: 'POST',
7142
- headers: {
7143
- 'Content-Type': 'application/json',
7144
- },
7145
- body: credentials,
7146
- } );
7147
-
7148
- const invalidateData = await invalidateRes.json();
7149
- console.log( 'Invalidate response:', invalidateData );
7150
-
7151
- console.log( 'Fetching new token...' );
7152
- const tokenRes = await fetchWithCookies( tokenUrl, {
7153
- method: 'POST',
7154
- headers: {
7155
- 'Content-Type': 'application/json',
7156
- 'Accept': 'application/json, text/javascript, */*; q=0.01',
7157
- },
7158
- body: credentials,
7159
- } );
7160
-
7161
- const tokenData = await tokenRes.json();
7162
- console.log( 'Token response:', tokenData );
7108
+ workbook.Sheets[sheetName] = newSheet;
7163
7109
 
7164
- return tokenData.access;
7165
- } catch ( error ) {
7166
- console.error( 'Error fetching new token:', error );
7167
- throw error;
7168
- }
7169
- };
7110
+ xlsx.writeFile( workbook, outputPath );
7111
+ }
7170
7112
 
7171
- const fetchVmImage = async ( attachmentId ) => {
7172
- try {
7173
- const response = await fetchWithCookies( `https://api.getcrest.ai/api/ms_data_preparation/master_data/attachment/?preview=0&attachment_id=${attachmentId}`, {
7174
- method: 'GET',
7175
- headers: {
7176
- 'Authorization': `Bearer ${staticToken}`,
7177
- 'Cookie': 'prod_session_key=w144dqljxlh096487nc33rm09vwtossh',
7178
- },
7179
- } );
7113
+ // fillFeedbackFromJson('input.xlsx', feedbackJson, 'output.xlsx');
7180
7114
 
7181
7115
 
7182
- if ( !response.ok ) {
7183
- return;
7184
- // throw new Error( `Failed to fetch image: ${response.status}` );
7185
- }
7116
+ function exportFixtureJsonToExcel( fixtures, filePath ) {
7117
+ const fixtureInfoArr = [];
7118
+ const shelfConfigArr = [];
7119
+ const vmConfigArr = [];
7186
7120
 
7187
- // const dest = fs.createWriteStream( `${attachmentId}.png` );
7188
- // response.body.pipe( dest );
7121
+ for ( const fixture of fixtures ) {
7122
+ fixtureInfoArr.push( {
7123
+ clientId: fixture.clientId,
7124
+ fixtureCode: fixture.fixtureCode,
7125
+ fixtureCategory: fixture.fixtureCategory,
7126
+ fixtureConfigType: fixture.fixtureConfigType,
7127
+ fixtureLength: `${fixture.fixtureLength?.value} ${fixture.fixtureLength?.unit}`,
7128
+ fixtureCapacity: fixture.fixtureCapacity,
7129
+ } );
7189
7130
 
7190
- return await response.buffer();
7191
- } catch ( error ) {
7192
- console.error( 'Error fetching image buffer:', error.message );
7193
- throw error;
7194
- }
7195
- };
7131
+ ( fixture.shelfConfig || [] ).forEach( ( shelf ) => {
7132
+ shelfConfigArr.push( {
7133
+ fixtureCode: fixture.fixtureCode,
7134
+ ...shelf,
7135
+ } );
7136
+ } );
7196
7137
 
7197
- const getImageMetadata = async ( imageBuffer ) => {
7198
- try {
7199
- const metadata = await sharp( imageBuffer ).metadata();
7200
- const { width, height, format } = metadata;
7138
+ ( fixture.vmConfig || [] ).forEach( ( vm ) => {
7139
+ vmConfigArr.push( {
7140
+ fixtureCode: fixture.fixtureCode,
7141
+ ...vm,
7142
+ } );
7143
+ } );
7144
+ }
7201
7145
 
7202
- if ( !width || !height || !format ) throw new Error( 'Invalid image metadata' );
7146
+ const workbook = xlsx.utils.book_new();
7147
+ xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( fixtureInfoArr ), 'Fixture Info' );
7148
+ xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( shelfConfigArr ), 'Shelf Config' );
7149
+ xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( vmConfigArr ), 'VM Config' );
7203
7150
 
7204
- const ratio = width / height;
7205
- const normalizedRatio = ratio > 1 ? ratio : 1 / ratio;
7206
- const squareThreshold = 1.2;
7207
- const imageShape = normalizedRatio <= squareThreshold ? 'square' : 'rectangle';
7208
-
7209
- const fileExtension = format === 'jpeg' ? 'jpg' : format;
7210
- const contentType = `image/${format}`;
7211
-
7212
- return {
7213
- imageShape,
7214
- width,
7215
- height,
7216
- fileExtension,
7217
- contentType,
7218
- };
7219
- } catch ( error ) {
7220
- console.error( 'Error processing image buffer:', error.message );
7221
- throw error;
7222
- }
7223
- };
7224
-
7225
-
7226
- async function generateFixtureTemplateName( baseName, fixtureWidth ) {
7227
- function escapeRegex( str ) {
7228
- return str.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' );
7229
- }
7230
-
7231
- const escapedBase = escapeRegex( baseName );
7232
- const regexPattern = new RegExp( `^Template-(\\d+)-${escapedBase}$` );
7233
-
7234
- const existingFixtures = await fixtureConfigService.find( {
7235
- fixtureName: { $regex: new RegExp( `^Template-(\\d+)-${escapedBase}$` ) },
7236
- fixtureWidth: fixtureWidth,
7237
- } );
7238
-
7239
- const usedNumbers = existingFixtures
7240
- .map( ( doc ) => {
7241
- const match = doc.fixtureName.match( regexPattern );
7242
- return match ? parseInt( match[1], 10 ) : null;
7243
- } )
7244
- .filter( ( num ) => num !== null );
7245
-
7246
- const nextNumber = usedNumbers.length > 0 ? Math.max( ...usedNumbers ) + 1 : 1;
7247
-
7248
- return `Template-${nextNumber}-${baseName}`;
7249
- }
7250
-
7251
-
7252
- if ( !req?.body?.storeName ) {
7253
- return res.sendError( 'No store supplied', 200 );
7254
- }
7255
-
7256
- let storeQuery = {
7257
- clientId: '11',
7258
- $and: [
7259
- { storeName: req.body.storeName },
7260
- // { storeName: { $in: [ 'LKST98' ] } },
7261
- // { storeName: { $nin: [ 'LKST98', 'LKST1193' ] } },
7262
- ],
7263
- };
7264
-
7265
- let storeList = await storeService.find( storeQuery );
7266
-
7267
- // const constantFixtureLength = 1220;
7268
- const constantDetailedFixtureLength = 1220;
7269
-
7270
- // const constantFixtureWidth = 610;
7271
- const constantDetailedFixtureWidth = 1524;
7272
-
7273
- const mmToFeet = 305;
7274
-
7275
- function roundToTwo( num ) {
7276
- return Math.round( num * 100 ) / 100;
7277
- }
7278
-
7279
-
7280
- for ( let i = 0; i < storeList.length; i++ ) {
7281
- const storeData = await fetchStoreData( storeList[i], staticToken, res );
7282
-
7283
- if ( storeData?.data?.message !== 'SUCCESS' ) continue;
7284
-
7285
-
7286
- const storeDetails = storeList[i];
7287
-
7288
- const existingPlanogram = await planoService.findOne( { storeName: storeData.storeName } );
7289
-
7290
- if ( existingPlanogram ) {
7291
- const checkTaskSubmitted = await planoTaskService.findOne( { planoId: existingPlanogram.toObject()._id } );
7292
-
7293
- const checkTaskCreated = await processedTaskService.findOne( { storeName: storeData.storeName, date_string: dayjs().format( 'YYYY-MM-DD' ), isPlano: true } );
7294
-
7295
- if ( checkTaskSubmitted || checkTaskCreated ) {
7296
- continue;
7297
- }
7298
- }
7299
-
7300
-
7301
- if ( existingPlanogram?.toObject()?._id && mongoose.Types.ObjectId.isValid( existingPlanogram?.toObject()?._id ) ) {
7302
- await Promise.all( [ planoService.deleteOne( { _id: existingPlanogram?.toObject()?._id } ), storeBuilderService.deleteMany( { planoId: existingPlanogram?.toObject()?._id } ),
7303
- storeFixtureService.deleteMany( { planoId: existingPlanogram?.toObject()?._id } ), fixtureShelfService.deleteMany( { planoId: existingPlanogram?.toObject()?._id } ),
7304
- planoMappingService.deleteMany( { planoId: existingPlanogram?.toObject()?._id } ),
7305
- ] );
7306
- }
7307
-
7308
-
7309
- const planoInsertData = {
7310
- storeName: storeData.storeName,
7311
- storeId: storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7312
- layoutName: `${storeData.storeName} - Layout`,
7313
- clientId: '11',
7314
- attachments: [],
7315
- createdBy: new mongoose.Types.ObjectId( '66a78cd82734f4f857cd6db6' ),
7316
- createdByName: 'Bejan',
7317
- createdByEmail: 'bejan@tangotech.co.in',
7318
- status: 'completed',
7319
- floorNumber: 1,
7320
- productResolutionLevel: 'L2',
7321
- scanType: 'qr',
7322
- };
7323
-
7324
- const insertedPlano = await planoService.upsertOne( { storeName: storeData.storeName }, planoInsertData );
7325
- const planoDoc = insertedPlano.toObject();
7326
-
7327
- const floors = new Set();
7328
-
7329
- for ( const item of storeData.data.result ) {
7330
- if ( item.floor ) {
7331
- floors.add( item.floor );
7332
- }
7333
-
7334
- if ( Array.isArray( item.fixtures ) ) {
7335
- for ( const fixture of item.fixtures ) {
7336
- if ( fixture.floor ) {
7337
- floors.add( fixture.floor );
7338
- }
7339
- }
7340
- }
7341
- }
7342
-
7343
- const floorArray = Array.from( floors );
7344
-
7345
- let isFloorKeyExist = true;
7346
-
7347
- if ( !floorArray.length ) {
7348
- isFloorKeyExist = false;
7349
- floorArray.push( 'GROUND' );
7350
- }
7351
-
7352
- for ( let floorIndex = 0; floorIndex < floorArray.length; floorIndex++ ) {
7353
- const leftWall = storeData.data.result.filter( ( entry ) => entry['main'] === 'LEFT WALL' );
7354
- let leftFixtures = leftWall.flatMap( ( wall ) => wall.fixtures );
7355
- if ( isFloorKeyExist ) {
7356
- leftFixtures = leftFixtures.filter( ( fixture ) => fixture.floor === floorArray[floorIndex] );
7357
- }
7358
- const rightWall = storeData.data.result.filter( ( entry ) => entry['main'] === 'RIGHT WALL' );
7359
- let rightFixtures = rightWall.flatMap( ( wall ) => wall.fixtures );
7360
- if ( isFloorKeyExist ) {
7361
- rightFixtures = rightFixtures.filter( ( fixture ) => fixture.floor === floorArray[floorIndex] );
7362
- }
7363
- const backWall = storeData.data.result.filter( ( entry ) => entry['main'] === 'RIGHT VERTICAL WALL' );
7364
- let backFixtures = backWall.flatMap( ( wall ) => wall.fixtures );
7365
- if ( isFloorKeyExist ) {
7366
- backFixtures = backFixtures.filter( ( fixture ) => fixture.floor === floorArray[floorIndex] );
7367
- }
7368
- let floorFixtures = storeData.data.result.filter(
7369
- ( entry ) => entry['main'] === 'Euro Center' || entry['main'] === 'Euro Center Dr',
7370
- );
7371
- if ( isFloorKeyExist ) {
7372
- floorFixtures = floorFixtures.filter( ( fixture ) => fixture.floor === floorArray[floorIndex] );
7373
- }
7374
-
7375
- // const leftXDistanceFeet = leftFixtures.length ? roundToTwo( ( leftFixtures.length * ( constantFixtureLength / mmToFeet ) ) ) : 0;
7376
- const leftXDetailedDistanceFeet = leftFixtures.length ? roundToTwo( ( leftFixtures.length * ( constantDetailedFixtureLength / mmToFeet ) ) ) : 0;
7377
-
7378
- // const leftYDistanceFeet = leftFixtures.length ? roundToTwo( ( ( constantFixtureWidth / mmToFeet ) ) ) : 0;
7379
- const leftYDetailedDistanceFeet = leftFixtures.length ? roundToTwo( ( ( constantDetailedFixtureWidth / mmToFeet ) ) ) : 0;
7380
-
7381
- // const rightXDistanceFeet = rightFixtures.length ? roundToTwo( ( rightFixtures.length * ( constantFixtureLength / mmToFeet ) ) ) : 0;
7382
- const rightXDetailedDistanceFeet = rightFixtures.length ? roundToTwo( ( rightFixtures.length * ( constantDetailedFixtureLength / mmToFeet ) ) ) : 0;
7383
-
7384
- // const rightYDistanceFeet = rightFixtures.length ? roundToTwo( ( constantFixtureWidth / mmToFeet ) ) : 0;
7385
- const rightYDetailedDistanceFeet = rightFixtures.length ? roundToTwo( ( constantDetailedFixtureWidth / mmToFeet ) ): 0;
7386
-
7387
- const maxFixturesPerRow = floorFixtures.length/2;
7388
- const totalRows = 2;
7389
-
7390
- // const floorXDistanceFeet = floorFixtures.length ? roundToTwo( ( ( floorFixtures.length/2 ) * ( constantFixtureLength / mmToFeet ) ) ) : 0;
7391
- const floorXDetailedDistanceFeet = floorFixtures.length ? roundToTwo( ( ( floorFixtures.length/2 ) * ( constantDetailedFixtureLength / mmToFeet ) ) ): 0;
7392
-
7393
- // const floorYDistanceFeet = floorFixtures.length ? roundToTwo( ( 2 * ( constantFixtureWidth/ mmToFeet ) ) ): 0;
7394
- const floorYDetailedDistanceFeet = floorFixtures.length ? roundToTwo( 2 * ( constantDetailedFixtureWidth/mmToFeet ) ): 0;
7395
-
7396
- // const backXDistanceFeet = backFixtures.length ? roundToTwo( ( constantFixtureWidth / mmToFeet ) ) : 0;
7397
- const backXDetailedDistanceFeet = backFixtures.length ? roundToTwo( ( constantDetailedFixtureLength / mmToFeet ) ) : 0;
7398
-
7399
- // const backYDistanceFeet = backFixtures.length ? roundToTwo( ( ( backFixtures.length * ( constantFixtureLength / mmToFeet ) ) + ( ( ( leftFixtures.length ? 1 : 0 ) + ( rightFixtures.length ? 1 : 0 ) * constantFixtureWidth )/mmToFeet ) ) ) : 0;
7400
- const backYDetailedDistanceFeet = backFixtures.length ? roundToTwo( ( ( backFixtures.length * ( constantDetailedFixtureWidth / mmToFeet ) ) + ( ( ( leftFixtures.length ? 1 : 0 ) + ( rightFixtures.length ? 1 : 0 ) * constantDetailedFixtureWidth )/mmToFeet ) ) ): 0;
7401
-
7402
- // const maxXDistance = Math.max( leftXDistanceFeet, rightXDistanceFeet, floorXDistanceFeet );
7403
- const maxXDetailedDistance = Math.max( leftXDetailedDistanceFeet, rightXDetailedDistanceFeet, floorXDetailedDistanceFeet );
7404
-
7405
- // const maxYDistance = Math.max( floorYDistanceFeet, backYDistanceFeet );
7406
- const maxYDetailedDistance = Math.max( floorYDetailedDistanceFeet, backYDetailedDistanceFeet );
7407
-
7408
- // const finalXDistance = roundToTwo( ( maxXDistance < ( backXDistanceFeet + floorXDistanceFeet )? ( ( backXDistanceFeet + floorXDistanceFeet ) + ( ( 2 * constantFixtureLength )/mmToFeet ) ) : ( floorFixtures.length && backFixtures.length ) ? ( maxXDistance + ( ( 2 * constantFixtureLength )/mmToFeet ) ) : maxXDistance ) );
7409
- const finalXDetailedDistance = roundToTwo( ( maxXDetailedDistance < ( backXDetailedDistanceFeet + floorXDetailedDistanceFeet )? ( ( backXDetailedDistanceFeet + floorXDetailedDistanceFeet ) + ( ( 2 * constantDetailedFixtureLength )/mmToFeet ) ) : ( floorFixtures.length && backFixtures.length ) ? ( maxXDetailedDistance + ( ( 2 * constantDetailedFixtureLength )/mmToFeet ) ) : maxXDetailedDistance ) );
7410
-
7411
- // const finalYDistance = roundToTwo( ( maxYDistance < ( leftYDistanceFeet + rightYDistanceFeet + floorYDistanceFeet ) ? ( ( leftYDistanceFeet + rightYDistanceFeet + floorYDistanceFeet ) + ( ( 2 * constantFixtureWidth )/mmToFeet ) ) : ( maxYDistance + ( ( constantFixtureWidth )/mmToFeet ) ) ) );
7412
- const finalYDetailedDistance = roundToTwo( ( maxYDetailedDistance < ( leftYDetailedDistanceFeet + rightYDetailedDistanceFeet + floorYDetailedDistanceFeet ) ? ( ( leftYDetailedDistanceFeet + rightYDetailedDistanceFeet + floorYDetailedDistanceFeet ) + ( ( 2 * constantDetailedFixtureWidth )/mmToFeet ) ) : ( maxYDetailedDistance + ( ( constantDetailedFixtureWidth )/mmToFeet ) ) ) );
7413
-
7414
-
7415
- const floorInsertData = {
7416
- storeName: planoDoc.storeName,
7417
- storeId: storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7418
- layoutName: `${planoDoc.storeName} - Layout`,
7419
- clientId: '11',
7420
- floorNumber: floorIndex + 1,
7421
- floorName: `${floorArray[floorIndex].toLowerCase()} floor`,
7422
- crestLayout: true,
7423
- layoutPolygon: [
7424
- {
7425
- elementType: 'wall',
7426
- distance: finalXDetailedDistance,
7427
- unit: 'ft',
7428
- direction: 'right',
7429
- angle: 90,
7430
- elementNumber: 1,
7431
- // detailedDistance: finalXDetailedDistance,
7432
- },
7433
- {
7434
- elementType: 'wall',
7435
- distance: finalYDetailedDistance,
7436
- unit: 'ft',
7437
- direction: 'down',
7438
- angle: 90,
7439
- elementNumber: 2,
7440
- // detailedDistance: finalYDetailedDistance,
7441
- },
7442
- {
7443
- elementType: 'wall',
7444
- distance: finalXDetailedDistance,
7445
- unit: 'ft',
7446
- direction: 'left',
7447
- angle: 90,
7448
- elementNumber: 3,
7449
- // detailedDistance: finalXDetailedDistance,
7450
- },
7451
- {
7452
- elementType: 'wall',
7453
- distance: roundToTwo( ( ( finalYDetailedDistance * 35 ) / 100 ) ),
7454
- unit: 'ft',
7455
- direction: 'up',
7456
- angle: 90,
7457
- elementNumber: 4,
7458
- // detailedDistance: roundToTwo( ( ( finalYDetailedDistance * 35 ) / 100 ) ),
7459
- },
7460
- {
7461
- elementType: 'entrance',
7462
- distance: roundToTwo( ( ( finalYDetailedDistance * 30 ) / 100 ) ),
7463
- unit: 'ft',
7464
- direction: 'up',
7465
- angle: 90,
7466
- elementNumber: 1,
7467
- // detailedDistance: roundToTwo( ( ( finalYDetailedDistance * 30 ) / 100 ) ),
7468
- },
7469
- {
7470
- elementType: 'wall',
7471
- distance: roundToTwo( ( ( finalYDetailedDistance * 35 ) / 100 ) ),
7472
- unit: 'ft',
7473
- direction: 'up',
7474
- angle: 90,
7475
- elementNumber: 5,
7476
- // detailedDistance: roundToTwo( ( ( finalYDetailedDistance * 35 ) / 100 ) ),
7477
- },
7478
- ],
7479
- createdBy: new mongoose.Types.ObjectId( '66a78cd82734f4f857cd6db6' ),
7480
- createdByName: 'Bejan',
7481
- createdByEmail: 'bejan@tangotech.co.in',
7482
- status: 'completed',
7483
- planoId: planoDoc._id,
7484
- };
7485
-
7486
- const layoutDoc = await storeBuilderService.upsertOne( { planoId: planoDoc._id, floorNumber: floorIndex + 1 }, floorInsertData );
7487
-
7488
- let fixtureCounter = 1;
7489
-
7490
-
7491
- for ( let index = 0; index < leftFixtures.length; index++ ) {
7492
- const fixture = leftFixtures[index];
7493
-
7494
- const fixtureConfig = await fixtureLibraryService.findOne( { fixtureCategory: fixture.fixtureType } );
7495
- if ( !fixtureConfig ) continue;
7496
- const fixtureConfigDoc = fixtureConfig.toObject();
7497
-
7498
- let mapKey = `${fixtureConfigDoc.fixtureCategory}${fixtureConfigDoc.fixtureWidth.value}${fixtureConfigDoc.fixtureWidth.unit},${fixture.header}`;
7499
-
7500
- const fixtureProductSubBrandName = new Set();
7501
-
7502
-
7503
- const shelfTemplate = fixtureConfigDoc.shelfConfig.map( ( configShelf, j ) => {
7504
- const shelfZone = fixture.productZones.find( ( zone ) => zone.zoneName === configShelf.shelfZone );
7505
- const shelfSection = shelfZone?.products.find( ( product ) => !product.isMerchandisingElement );
7506
-
7507
- const shelfIdentifier = `shelf${j + 1}=${shelfSection?.productName}`;
7508
-
7509
- mapKey += ','+shelfIdentifier;
7510
-
7511
- const productSubBrandName = shelfSection?.productName?.replace( /\s*PIDs\b/g, '' )?.split( /\s*\+\s*/ ) || [];
7512
-
7513
- productSubBrandName.forEach( ( item ) => fixtureProductSubBrandName.add( item ) );
7514
-
7515
- return {
7516
- shelfNumber: j+1,
7517
- shelfType: configShelf?.shelfType,
7518
- productPerShelf: configShelf?.productPerShelf,
7519
- trayRows: configShelf?.trayRows,
7520
- productBrandName: productSubBrandName,
7521
- zone: configShelf.shelfZone,
7522
- };
7523
- } );
7524
-
7525
- const vmConfig = fixture.productZones?.flatMap( ( zone ) => {
7526
- const vms = zone.products.filter( ( vm ) => vm.isMerchandisingElement );
7527
- const vmConfig = fixtureConfigDoc.vmConfig.filter( ( vm ) => vm.position === zone.zoneName );
7528
- const pids = zone.products.filter( ( vm ) => !vm.isMerchandisingElement );
7529
-
7530
- return vms.map( ( vm, k ) => {
7531
- let configData = vmConfig[0];
7532
-
7533
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' ) {
7534
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 905 );
7535
- configData.zone = 'stretch';
7536
- }
7537
-
7538
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' && pids.length ) {
7539
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 230 );
7540
- }
7541
-
7542
- if ( !configData ) return;
7543
-
7544
- const vmIdentifier = `vm${k+1}=${vm.productName}+${configData.vmHeightmm}+${configData.vmWidthmm}+${configData.startShelf}+${configData.endShelf}+${configData.zone}`;
7545
-
7546
- mapKey += ','+vmIdentifier;
7547
-
7548
- return {
7549
- startYPosition: configData.startShelf,
7550
- endYPosition: configData.endShelf,
7551
- xZone: configData.zone,
7552
- vmName: vm.productName,
7553
- vmHeight: configData.vmHeightmm,
7554
- vmWidth: configData.vmWidthmm,
7555
- imageUrl: zone?.actual_image_url,
7556
- };
7557
- } );
7558
- } );
7559
-
7560
- const vmTemplate = await Promise.all( vmConfig.map( async ( vmTemplate ) => {
7561
- const vmInsertData = {
7562
- clientId: '11',
7563
- vmName: vmTemplate.vmName,
7564
- vmHeight: {
7565
- value: vmTemplate.vmHeight,
7566
- unit: 'mm',
7567
- },
7568
- vmWidth: {
7569
- value: vmTemplate.vmWidth,
7570
- unit: 'mm',
7571
- },
7572
- status: 'complete',
7573
- vmBrand: vmTemplate.vmBrand,
7574
- };
7575
- if ( vmTemplate?.imageUrl ) {
7576
- const parsedUrl = new URL( vmTemplate.imageUrl );
7577
- const attachmentId = parsedUrl.searchParams.get( 'attachment_id' );
7578
-
7579
- const isVmImageExist = await planoVmService.findOne( { crestImageId: attachmentId } );
7580
-
7581
- if ( !isVmImageExist ) {
7582
- const vmImageData = await fetchVmImage( attachmentId );
7583
-
7584
- const imageMeta = await getImageMetadata( vmImageData );
7585
-
7586
- const params = {
7587
- Bucket: JSON.parse( process.env.BUCKET ).storeBuilder,
7588
- Key: `vmType/`,
7589
- fileName: `${attachmentId}.${imageMeta.fileExtension}`,
7590
- ContentType: imageMeta.contentType,
7591
- body: vmImageData,
7592
- };
7593
-
7594
- const imgUpload = await fileUpload( params );
7595
-
7596
- vmInsertData.crestImageId = attachmentId;
7597
- vmInsertData.vmImageUrl = imgUpload.Key;
7598
-
7599
-
7600
- if ( imageMeta.imageShape === 'square' ) {
7601
- vmInsertData.vmHeight.value = 100;
7602
- vmInsertData.vmWidth.value = 230;
7603
- }
7604
- } else {
7605
- vmInsertData.crestImageId = attachmentId;
7606
- vmInsertData.vmImageUrl = isVmImageExist.toObject().vmImageUrl;
7607
- }
7608
- }
7609
-
7610
- const vmDetails = await planoVmService.upsertOne(
7611
- {
7612
- 'productName': vmInsertData.vmName,
7613
- },
7614
- vmInsertData,
7615
- );
7616
-
7617
- return {
7618
- vmId: vmDetails.toObject()._id,
7619
- startYPosition: vmTemplate.startYPosition,
7620
- endYPosition: vmTemplate.endYPosition,
7621
- xZone: vmTemplate.xZone,
7622
- };
7623
- } ) );
7624
-
7625
- const baseFixtureName = `${fixtureConfigDoc.fixtureCategory}`;
7626
- const uniqueFixtureName = await generateFixtureTemplateName( baseFixtureName, fixtureConfigDoc.fixtureWidth );
7627
-
7628
-
7629
- const fixtureTemplateData = {
7630
- ...fixtureConfigDoc,
7631
- 'shelfConfig': shelfTemplate,
7632
- 'vmConfig': vmTemplate,
7633
- 'clientId': fixtureConfigDoc.clientId,
7634
- 'fixtureName': uniqueFixtureName,
7635
- 'header': {
7636
- label: fixture.header ? fixture.header : fixture.fixtureSubname[0],
7637
- isEnabled: true,
7638
- },
7639
- 'footer': {
7640
- label: fixture.footer,
7641
- isEnabled: true,
7642
- },
7643
- 'isBodyEnabled': true,
7644
- 'productResolutionLevel': 'L3',
7645
- 'productBrandName': [ ...fixtureProductSubBrandName ],
7646
- 'fixtureLibraryId': fixtureConfigDoc._id,
7647
- 'crestMapKey': mapKey,
7648
- };
7649
-
7650
- delete fixtureTemplateData._id;
7651
-
7652
-
7653
- const fixtureTemplate = await fixtureConfigService.upsertOne(
7654
- { crestMapKey: mapKey },
7655
- fixtureTemplateData,
7656
- );
7657
-
7658
- const fixtureData = {
7659
- ...fixtureTemplate.toObject(),
7660
- 'storeName': layoutDoc.storeName,
7661
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7662
- 'planoId': layoutDoc.planoId,
7663
- 'floorId': layoutDoc._id,
7664
- 'associatedElementType': 'wall',
7665
- 'associatedElementNumber': 1,
7666
- 'relativePosition': {
7667
- 'x': roundToTwo( ( index * ( constantDetailedFixtureLength / mmToFeet ) ) ),
7668
- 'y': 0,
7669
- 'unit': 'ft',
7670
- },
7671
- 'fixtureNumber': fixtureCounter,
7672
- // 'relativeDetailedPosition': {
7673
- // 'x': roundToTwo( ( index * ( constantDetailedFixtureLength / mmToFeet ) ) ),
7674
- // 'y': 0,
7675
- // 'unit': 'ft',
7676
- // },
7677
- 'associatedElementFixtureNumber': index+1,
7678
- 'fixtureConfigId': fixtureTemplate.toObject()._id,
7679
- };
7680
-
7681
- delete fixtureData._id;
7682
- delete fixtureData.shelfConfig;
7683
-
7684
- const createdFixture = await storeFixtureService.upsertOne(
7685
- {
7686
- floorId: layoutDoc._id,
7687
- fixtureNumber: fixtureCounter++,
7688
- },
7689
- fixtureData,
7690
- );
7691
-
7692
- if ( !fixtureConfigDoc.shelfConfig.length || fixture.header === 'CL' || fixture.fixtureSubname?.includes( 'CL' ) ) continue;
7693
-
7694
- fixtureTemplate.shelfConfig.forEach( async ( configShelf, j ) => {
7695
- const shelfData = {
7696
- 'clientId': '11',
7697
- 'storeName': layoutDoc.storeName,
7698
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7699
- 'planoId': layoutDoc.planoId,
7700
- 'floorId': layoutDoc._id,
7701
- 'fixtureId': createdFixture._id,
7702
- 'shelfNumber': j + 1,
7703
- 'shelfOrder': 'LTR',
7704
- 'shelfCapacity': configShelf.shelfCapacity,
7705
- 'productBrandName': configShelf.productBrandName,
7706
- 'shelfType': configShelf.shelfType,
7707
- 'productPerShelf': configShelf.productPerShelf,
7708
- 'trayRows': configShelf.trayRows,
7709
- 'productPerTray': configShelf.productPerTray,
7710
- 'zone': configShelf.zone,
7711
- };
7712
-
7713
- await fixtureShelfService.upsertOne(
7714
- {
7715
- fixtureId: createdFixture._id,
7716
- shelfNumber: j + 1,
7717
- },
7718
- shelfData,
7719
- );
7720
- } );
7721
- }
7722
-
7723
- for ( let index = 0; index < backFixtures.length; index++ ) {
7724
- const fixture = backFixtures[index];
7725
-
7726
- const fixtureConfig = await fixtureLibraryService.findOne( { fixtureCategory: fixture.fixtureType } );
7727
- if ( !fixtureConfig ) continue;
7728
- const fixtureConfigDoc = fixtureConfig.toObject();
7729
-
7730
- let mapKey = `${fixtureConfigDoc.fixtureCategory}${fixtureConfigDoc.fixtureWidth.value}${fixtureConfigDoc.fixtureWidth.unit},${fixture.header}`;
7731
-
7732
- const fixtureProductSubBrandName = new Set();
7733
-
7734
-
7735
- const shelfTemplate = fixtureConfigDoc.shelfConfig.map( ( configShelf, j ) => {
7736
- const shelfZone = fixture.productZones.find( ( zone ) => zone.zoneName === configShelf.shelfZone );
7737
- const shelfSection = shelfZone?.products.find( ( product ) => !product.isMerchandisingElement );
7738
-
7739
- const shelfIdentifier = `shelf${j + 1}=${shelfSection?.productName}`;
7740
-
7741
- mapKey += ','+shelfIdentifier;
7742
-
7743
- const productSubBrandName = shelfSection?.productName?.replace( /\s*PIDs\b/g, '' )?.split( /\s*\+\s*/ ) || [];
7744
-
7745
- productSubBrandName.forEach( ( item ) => fixtureProductSubBrandName.add( item ) );
7746
-
7747
- return {
7748
- shelfNumber: j+1,
7749
- shelfType: configShelf?.shelfType,
7750
- productPerShelf: configShelf?.productPerShelf,
7751
- trayRows: configShelf?.trayRows,
7752
- productBrandName: productSubBrandName,
7753
- zone: configShelf.shelfZone,
7754
- };
7755
- } );
7756
-
7757
- const vmConfig = fixture.productZones?.flatMap( ( zone ) => {
7758
- const vms = zone.products.filter( ( vm ) => vm.isMerchandisingElement );
7759
- const vmConfig = fixtureConfigDoc.vmConfig.filter( ( vm ) => vm.position === zone.zoneName );
7760
- const pids = zone.products.filter( ( vm ) => !vm.isMerchandisingElement );
7761
-
7762
- return vms.map( ( vm, k ) => {
7763
- let configData = vmConfig[0];
7764
-
7765
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' ) {
7766
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 905 );
7767
- configData.zone = 'stretch';
7768
- }
7769
-
7770
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' && pids.length ) {
7771
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 230 );
7772
- }
7773
-
7774
- if ( !configData ) return;
7775
-
7776
- const vmIdentifier = `vm${k+1}=${vm.productName}+${configData.vmHeightmm}+${configData.vmWidthmm}+${configData.startShelf}+${configData.endShelf}+${configData.zone}`;
7777
-
7778
- mapKey += ','+vmIdentifier;
7779
-
7780
- return {
7781
- startYPosition: configData.startShelf,
7782
- endYPosition: configData.endShelf,
7783
- xZone: configData.zone,
7784
- vmName: vm.productName,
7785
- vmHeight: configData.vmHeightmm,
7786
- vmWidth: configData.vmWidthmm,
7787
- imageUrl: zone?.actual_image_url,
7788
- };
7789
- } );
7790
- } );
7791
-
7792
- const vmTemplate = await Promise.all( vmConfig.map( async ( vmTemplate ) => {
7793
- const vmInsertData = {
7794
- clientId: '11',
7795
- vmName: vmTemplate.vmName,
7796
- vmHeight: {
7797
- value: vmTemplate.vmHeight,
7798
- unit: 'mm',
7799
- },
7800
- vmWidth: {
7801
- value: vmTemplate.vmWidth,
7802
- unit: 'mm',
7803
- },
7804
- status: 'complete',
7805
- vmBrand: vmTemplate.vmBrand,
7806
- };
7807
- if ( vmTemplate?.imageUrl ) {
7808
- const parsedUrl = new URL( vmTemplate.imageUrl );
7809
- const attachmentId = parsedUrl.searchParams.get( 'attachment_id' );
7810
-
7811
- const isVmImageExist = await planoVmService.findOne( { crestImageId: attachmentId } );
7812
-
7813
- if ( !isVmImageExist ) {
7814
- const vmImageData = await fetchVmImage( attachmentId );
7815
-
7816
- const imageMeta = await getImageMetadata( vmImageData );
7817
-
7818
- const params = {
7819
- Bucket: JSON.parse( process.env.BUCKET ).storeBuilder,
7820
- Key: `vmType/`,
7821
- fileName: `${attachmentId}.${imageMeta.fileExtension}`,
7822
- ContentType: imageMeta.contentType,
7823
- body: vmImageData,
7824
- };
7825
-
7826
- const imgUpload = await fileUpload( params );
7827
-
7828
-
7829
- vmInsertData.crestImageId = attachmentId;
7830
- vmInsertData.vmImageUrl = imgUpload.Key;
7831
-
7832
-
7833
- if ( imageMeta.imageShape === 'square' ) {
7834
- vmInsertData.vmHeight.value = 100;
7835
- vmInsertData.vmWidth.value = 230;
7836
- }
7837
- } else {
7838
- vmInsertData.crestImageId = attachmentId;
7839
- vmInsertData.vmImageUrl = isVmImageExist.toObject().vmImageUrl;
7840
- }
7841
- }
7842
-
7843
- const vmDetails = await planoVmService.upsertOne(
7844
- {
7845
- 'productName': vmInsertData.vmName,
7846
- },
7847
- vmInsertData,
7848
- );
7849
-
7850
- return {
7851
- vmId: vmDetails.toObject()._id,
7852
- startYPosition: vmTemplate.startYPosition,
7853
- endYPosition: vmTemplate.endYPosition,
7854
- xZone: vmTemplate.xZone,
7855
- };
7856
- } ) );
7857
-
7858
- const baseFixtureName = `${fixtureConfigDoc.fixtureCategory}`;
7859
- const uniqueFixtureName = await generateFixtureTemplateName( baseFixtureName, fixtureConfigDoc.fixtureWidth );
7860
-
7861
-
7862
- const fixtureTemplateData = {
7863
- ...fixtureConfigDoc,
7864
- 'shelfConfig': shelfTemplate,
7865
- 'vmConfig': vmTemplate,
7866
- 'clientId': fixtureConfigDoc.clientId,
7867
- 'fixtureName': uniqueFixtureName,
7868
- 'header': {
7869
- label: fixture.header ? fixture.header : fixture.fixtureSubname[0],
7870
- isEnabled: true,
7871
- },
7872
- 'footer': {
7873
- label: fixture.footer,
7874
- isEnabled: true,
7875
- },
7876
- 'isBodyEnabled': true,
7877
- 'productResolutionLevel': 'L3',
7878
- 'productBrandName': [ ...fixtureProductSubBrandName ],
7879
- 'fixtureLibraryId': fixtureConfigDoc._id,
7880
- 'crestMapKey': mapKey,
7881
- };
7882
-
7883
- delete fixtureTemplateData._id;
7884
-
7885
-
7886
- const fixtureTemplate = await fixtureConfigService.upsertOne(
7887
- { crestMapKey: mapKey },
7888
- fixtureTemplateData,
7889
- );
7890
-
7891
- const fixtureData = {
7892
- ...fixtureTemplate.toObject(),
7893
- 'storeName': layoutDoc.storeName,
7894
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7895
- 'planoId': layoutDoc.planoId,
7896
- 'floorId': layoutDoc._id,
7897
- 'associatedElementType': 'wall',
7898
- 'associatedElementNumber': 2,
7899
- 'relativePosition': {
7900
- 'x': roundToTwo( ( finalXDetailedDistance - ( constantDetailedFixtureLength/mmToFeet ) ) ),
7901
- 'y': roundToTwo( ( ( index * ( ( constantDetailedFixtureWidth/mmToFeet ) ) ) + ( ( leftFixtures.length ? 1 : 0 ) * constantDetailedFixtureWidth/mmToFeet ) ) ),
7902
- 'unit': 'ft',
7903
- },
7904
- 'fixtureNumber': fixtureCounter,
7905
- // 'relativeDetailedPosition': {
7906
- // 'x': roundToTwo( ( finalXDetailedDistance - ( constantDetailedFixtureLength/mmToFeet ) ) ),
7907
- // 'y': roundToTwo( ( ( index * ( ( constantDetailedFixtureWidth/mmToFeet ) ) ) + ( ( leftFixtures.length ? 1 : 0 ) * constantDetailedFixtureWidth/mmToFeet ) ) ),
7908
- // 'unit': 'ft',
7909
- // },
7910
- 'associatedElementFixtureNumber': index+1,
7911
- 'fixtureConfigId': fixtureTemplate.toObject()._id,
7912
- };
7913
-
7914
- delete fixtureData._id;
7915
- delete fixtureData.shelfConfig;
7916
-
7917
- const createdFixture = await storeFixtureService.upsertOne(
7918
- {
7919
- floorId: layoutDoc._id,
7920
- fixtureNumber: fixtureCounter++,
7921
- },
7922
- fixtureData,
7923
- );
7924
-
7925
- if ( !fixtureConfigDoc.shelfConfig.length || fixture.header === 'CL' || fixture.fixtureSubname?.includes( 'CL' ) ) continue;
7926
-
7927
- fixtureTemplate.shelfConfig.forEach( async ( configShelf, j ) => {
7928
- const shelfData = {
7929
- 'clientId': '11',
7930
- 'storeName': layoutDoc.storeName,
7931
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
7932
- 'planoId': layoutDoc.planoId,
7933
- 'floorId': layoutDoc._id,
7934
- 'fixtureId': createdFixture._id,
7935
- 'shelfNumber': j + 1,
7936
- 'shelfOrder': 'LTR',
7937
- 'shelfCapacity': configShelf.shelfCapacity,
7938
- 'productBrandName': configShelf.productBrandName,
7939
- 'shelfType': configShelf.shelfType,
7940
- 'productPerShelf': configShelf.productPerShelf,
7941
- 'trayRows': configShelf.trayRows,
7942
- 'productPerTray': configShelf.productPerTray,
7943
- 'zone': configShelf.zone,
7944
- };
7945
-
7946
- await fixtureShelfService.upsertOne(
7947
- {
7948
- fixtureId: createdFixture._id,
7949
- shelfNumber: j + 1,
7950
- },
7951
- shelfData,
7952
- );
7953
- } );
7954
- }
7955
-
7956
- for ( let index = 0; index < rightFixtures.length; index++ ) {
7957
- const fixture = rightFixtures[index];
7958
-
7959
- const fixtureConfig = await fixtureLibraryService.findOne( { fixtureCategory: fixture.fixtureType } );
7960
- if ( !fixtureConfig ) continue;
7961
- const fixtureConfigDoc = fixtureConfig.toObject();
7962
-
7963
- let mapKey = `${fixtureConfigDoc.fixtureCategory}${fixtureConfigDoc.fixtureWidth.value}${fixtureConfigDoc.fixtureWidth.unit},${fixture.header}`;
7964
-
7965
- const fixtureProductSubBrandName = new Set();
7966
-
7967
-
7968
- const shelfTemplate = fixtureConfigDoc.shelfConfig.map( ( configShelf, j ) => {
7969
- const shelfZone = fixture.productZones.find( ( zone ) => zone.zoneName === configShelf.shelfZone );
7970
- const shelfSection = shelfZone?.products.find( ( product ) => !product.isMerchandisingElement );
7971
-
7972
- const shelfIdentifier = `shelf${j + 1}=${shelfSection?.productName}`;
7973
-
7974
- mapKey += ','+shelfIdentifier;
7975
-
7976
- const productSubBrandName = shelfSection?.productName?.replace( /\s*PIDs\b/g, '' )?.split( /\s*\+\s*/ ) || [];
7977
-
7978
- productSubBrandName.forEach( ( item ) => fixtureProductSubBrandName.add( item ) );
7979
-
7980
- return {
7981
- shelfNumber: j+1,
7982
- shelfType: configShelf?.shelfType,
7983
- productPerShelf: configShelf?.productPerShelf,
7984
- trayRows: configShelf?.trayRows,
7985
- productBrandName: productSubBrandName,
7986
- zone: configShelf.shelfZone,
7987
- };
7988
- } );
7989
-
7990
- const vmConfig = fixture.productZones?.flatMap( ( zone ) => {
7991
- const vms = zone.products.filter( ( vm ) => vm.isMerchandisingElement );
7992
- const vmConfig = fixtureConfigDoc.vmConfig.filter( ( vm ) => vm.position === zone.zoneName );
7993
- const pids = zone.products.filter( ( vm ) => !vm.isMerchandisingElement );
7994
-
7995
- return vms.map( ( vm, k ) => {
7996
- let configData = vmConfig[0];
7997
-
7998
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' ) {
7999
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 905 );
8000
- configData.zone = 'stretch';
8001
- }
8002
-
8003
- if ( vm.productName === 'Creatr' && zone.zoneName === 'Mid' && pids.length ) {
8004
- configData = vmConfig.find( ( config ) => config.vmWidthmm === 230 );
8005
- }
8006
-
8007
- if ( !configData ) return;
8008
-
8009
- const vmIdentifier = `vm${k+1}=${vm.productName}+${configData.vmHeightmm}+${configData.vmWidthmm}+${configData.startShelf}+${configData.endShelf}+${configData.zone}`;
8010
-
8011
- mapKey += ','+vmIdentifier;
8012
-
8013
- return {
8014
- startYPosition: configData.startShelf,
8015
- endYPosition: configData.endShelf,
8016
- xZone: configData.zone,
8017
- vmName: vm.productName,
8018
- vmHeight: configData.vmHeightmm,
8019
- vmWidth: configData.vmWidthmm,
8020
- imageUrl: zone?.actual_image_url,
8021
- };
8022
- } );
8023
- } );
8024
-
8025
- const vmTemplate = await Promise.all( vmConfig.map( async ( vmTemplate ) => {
8026
- const vmInsertData = {
8027
- clientId: '11',
8028
- vmName: vmTemplate.vmName,
8029
- vmHeight: {
8030
- value: vmTemplate.vmHeight,
8031
- unit: 'mm',
8032
- },
8033
- vmWidth: {
8034
- value: vmTemplate.vmWidth,
8035
- unit: 'mm',
8036
- },
8037
- status: 'complete',
8038
- vmBrand: vmTemplate.vmBrand,
8039
- };
8040
- if ( vmTemplate?.imageUrl ) {
8041
- const parsedUrl = new URL( vmTemplate.imageUrl );
8042
- const attachmentId = parsedUrl.searchParams.get( 'attachment_id' );
8043
-
8044
- const isVmImageExist = await planoVmService.findOne( { crestImageId: attachmentId } );
8045
-
8046
- if ( !isVmImageExist ) {
8047
- const vmImageData = await fetchVmImage( attachmentId );
8048
-
8049
- const imageMeta = await getImageMetadata( vmImageData );
8050
-
8051
- const params = {
8052
- Bucket: JSON.parse( process.env.BUCKET ).storeBuilder,
8053
- Key: `vmType/`,
8054
- fileName: `${attachmentId}.${imageMeta.fileExtension}`,
8055
- ContentType: imageMeta.contentType,
8056
- body: vmImageData,
8057
- };
8058
-
8059
- const imgUpload = await fileUpload( params );
8060
-
8061
- vmInsertData.crestImageId = attachmentId;
8062
- vmInsertData.vmImageUrl = imgUpload.Key;
8063
-
8064
-
8065
- if ( imageMeta.imageShape === 'square' ) {
8066
- vmInsertData.vmHeight.value = 100;
8067
- vmInsertData.vmWidth.value = 230;
8068
- }
8069
- } else {
8070
- vmInsertData.crestImageId = attachmentId;
8071
- vmInsertData.vmImageUrl = isVmImageExist.toObject().vmImageUrl;
8072
- }
8073
- }
8074
-
8075
- const vmDetails = await planoVmService.upsertOne(
8076
- {
8077
- 'productName': vmInsertData.vmName,
8078
- },
8079
- vmInsertData,
8080
- );
8081
-
8082
- return {
8083
- vmId: vmDetails.toObject()._id,
8084
- startYPosition: vmTemplate.startYPosition,
8085
- endYPosition: vmTemplate.endYPosition,
8086
- xZone: vmTemplate.xZone,
8087
- };
8088
- } ) );
8089
-
8090
- const baseFixtureName = `${fixtureConfigDoc.fixtureCategory}`;
8091
- const uniqueFixtureName = await generateFixtureTemplateName( baseFixtureName, fixtureConfigDoc.fixtureWidth );
8092
-
8093
-
8094
- const fixtureTemplateData = {
8095
- ...fixtureConfigDoc,
8096
- 'shelfConfig': shelfTemplate,
8097
- 'vmConfig': vmTemplate,
8098
- 'clientId': fixtureConfigDoc.clientId,
8099
- 'fixtureName': uniqueFixtureName,
8100
- 'header': {
8101
- label: fixture.header ? fixture.header : fixture.fixtureSubname[0],
8102
- isEnabled: true,
8103
- },
8104
- 'footer': {
8105
- label: fixture.footer,
8106
- isEnabled: true,
8107
- },
8108
- 'isBodyEnabled': true,
8109
- 'productResolutionLevel': 'L3',
8110
- 'productBrandName': [ ...fixtureProductSubBrandName ],
8111
- 'fixtureLibraryId': fixtureConfigDoc._id,
8112
- 'crestMapKey': mapKey,
8113
- };
8114
-
8115
- delete fixtureTemplateData._id;
8116
-
8117
-
8118
- const fixtureTemplate = await fixtureConfigService.upsertOne(
8119
- { crestMapKey: mapKey },
8120
- fixtureTemplateData,
8121
- );
8122
-
8123
- const fixtureData = {
8124
- ...fixtureTemplate.toObject(),
8125
- 'storeName': layoutDoc.storeName,
8126
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
8127
- 'planoId': layoutDoc.planoId,
8128
- 'floorId': layoutDoc._id,
8129
- 'associatedElementType': 'wall',
8130
- 'associatedElementNumber': 3,
8131
- 'relativePosition': {
8132
- 'x': roundToTwo( ( index * ( constantDetailedFixtureLength / mmToFeet ) ) ),
8133
- 'y': roundToTwo( ( finalYDetailedDistance - ( constantDetailedFixtureWidth / mmToFeet ) ) ),
8134
- 'unit': 'ft',
8135
- },
8136
- 'fixtureNumber': fixtureCounter,
8137
- // 'relativeDetailedPosition': {
8138
- // 'x': roundToTwo( ( index * ( constantDetailedFixtureLength / mmToFeet ) ) ),
8139
- // 'y': roundToTwo( ( finalYDetailedDistance - ( constantDetailedFixtureWidth / mmToFeet ) ) ),
8140
- // 'unit': 'ft',
8141
- // },
8142
- 'associatedElementFixtureNumber': index+1,
8143
- 'fixtureConfigId': fixtureTemplate.toObject()._id,
8144
- };
8145
-
8146
- delete fixtureData._id;
8147
- delete fixtureData.shelfConfig;
8148
-
8149
- const createdFixture = await storeFixtureService.upsertOne(
8150
- {
8151
- floorId: layoutDoc._id,
8152
- fixtureNumber: fixtureCounter++,
8153
- },
8154
- fixtureData,
8155
- );
8156
-
8157
- if ( !fixtureConfigDoc.shelfConfig.length || fixture.header === 'CL' || fixture.fixtureSubname?.includes( 'CL' ) ) continue;
8158
-
8159
- fixtureTemplate.shelfConfig.forEach( async ( configShelf, j ) => {
8160
- const shelfData = {
8161
- 'clientId': '11',
8162
- 'storeName': layoutDoc.storeName,
8163
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
8164
- 'planoId': layoutDoc.planoId,
8165
- 'floorId': layoutDoc._id,
8166
- 'fixtureId': createdFixture._id,
8167
- 'shelfNumber': j + 1,
8168
- 'shelfOrder': 'LTR',
8169
- 'shelfCapacity': configShelf.shelfCapacity,
8170
- 'productBrandName': configShelf.productBrandName,
8171
- 'shelfType': configShelf.shelfType,
8172
- 'productPerShelf': configShelf.productPerShelf,
8173
- 'trayRows': configShelf.trayRows,
8174
- 'productPerTray': configShelf.productPerTray,
8175
- 'zone': configShelf.zone,
8176
- };
8177
-
8178
- await fixtureShelfService.upsertOne(
8179
- {
8180
- fixtureId: createdFixture._id,
8181
- shelfNumber: j + 1,
8182
- },
8183
- shelfData,
8184
- );
8185
- } );
8186
- }
8187
-
8188
- for ( let index = 0; index < floorFixtures.length; index++ ) {
8189
- const fixture = floorFixtures[index];
8190
-
8191
- const centerRow = Math.floor( totalRows / 2 );
8192
-
8193
- // const startingX = roundToTwo( ( finalXDistance / 2 - ( maxFixturesPerRow / 2 ) * ( constantFixtureLength / mmToFeet ) ) );
8194
- const detailedStartingX = roundToTwo( ( finalXDetailedDistance / 2 - ( maxFixturesPerRow / 2 ) * ( constantDetailedFixtureLength / mmToFeet ) ) );
8195
-
8196
- // const startingY = finalYDistance / 2 - centerRow * ( constantFixtureWidth / mmToFeet );
8197
- const detailedStartingY = finalYDetailedDistance / 2 - centerRow * ( constantDetailedFixtureWidth / mmToFeet );
8198
-
8199
- const colIndex = Math.floor( index / 2 );
8200
- const rowIndex = index % 2 === 0 ? 1 : 0;
8201
-
8202
- // const xPos = roundToTwo( startingX + colIndex * ( constantFixtureLength / mmToFeet ) );
8203
- // const yPos = roundToTwo( startingY + rowIndex * ( constantFixtureWidth / mmToFeet ) );
8204
-
8205
- const detailedXPos = roundToTwo( ( detailedStartingX + colIndex * ( constantDetailedFixtureLength / mmToFeet ) ) );
8206
- const detailedYPos = roundToTwo( ( detailedStartingY + rowIndex * ( constantDetailedFixtureWidth / mmToFeet ) ) );
8207
-
8208
- const fixtureConfig = await fixtureLibraryService.findOne( { fixtureCategory: fixture.main } );
8209
- if ( !fixtureConfig ) continue;
8210
- const fixtureConfigDoc = fixtureConfig.toObject();
8211
-
8212
- let mapKey = `${fixtureConfigDoc.fixtureCategory}${fixtureConfigDoc.fixtureWidth.value}${fixtureConfigDoc.fixtureWidth.unit},${fixture.header}`;
8213
-
8214
- const fixtureProductSubBrandName = new Set();
8215
-
8216
-
8217
- const shelfTemplate = fixtureConfigDoc.shelfConfig.map( ( configShelf, j ) => {
8218
- const shelfSection = fixture?.centerSuperSubMain?.find( ( product ) => !product.isVisualMerchandiser );
8219
-
8220
- const shelfIdentifier = `shelf${j + 1}=${shelfSection?.productName}`;
8221
-
8222
- mapKey += ','+shelfIdentifier;
8223
-
8224
-
8225
- let productSubBrandName = fixture.centerSubMain.replace( /\s*PIDs\b/g, '' )?.split( /\s*\+\s*/ ) || [];
8226
-
8227
- if ( shelfSection ) {
8228
- productSubBrandName = shelfSection.name.replace( /\s*PIDs\b/g, '' )?.split( /\s*\+\s*/ ) || [];
8229
- }
8230
-
8231
- productSubBrandName.forEach( ( item ) => fixtureProductSubBrandName.add( item ) );
8232
-
8233
- return {
8234
- shelfNumber: j+1,
8235
- shelfType: configShelf?.shelfType,
8236
- productPerShelf: configShelf?.productPerShelf,
8237
- trayRows: configShelf?.trayRows,
8238
- productBrandName: productSubBrandName,
8239
- zone: configShelf.shelfZone,
8240
- };
8241
- } );
8242
-
8243
- const vmConfig = fixture.centerSuperSubMain?.flatMap( ( vm ) => {
8244
- if ( !vm?.isVisualMerchandiser ) {
8245
- return [];
8246
- }
8247
- const vmConfig = fixtureConfigDoc.vmConfig;
8248
-
8249
- const [ configData1, configData2 ] = [ vmConfig[0], vmConfig[1] ];
8250
-
8251
- return [
8252
- {
8253
- startYPosition: configData1.startShelf,
8254
- endYPosition: configData1.endShelf,
8255
- xZone: configData1.zone,
8256
- vmName: vm.name + ' - 1',
8257
- vmHeight: configData1.vmHeightmm,
8258
- vmWidth: configData1.vmWidthmm,
8259
- },
8260
- {
8261
- startYPosition: configData2.startShelf,
8262
- endYPosition: configData2.endShelf,
8263
- xZone: configData2.zone,
8264
- vmName: vm.name + ' - 2',
8265
- vmHeight: configData2.vmHeightmm,
8266
- vmWidth: configData2.vmWidthmm,
8267
- },
8268
- ];
8269
- } );
8270
-
8271
- const vmTemplate = await Promise.all( vmConfig.map( async ( vmTemplate ) => {
8272
- const vmInsertData = {
8273
- clientId: '11',
8274
- vmName: vmTemplate.vmName,
8275
- vmHeight: {
8276
- value: vmTemplate.vmHeight,
8277
- unit: 'mm',
8278
- },
8279
- vmWidth: {
8280
- value: vmTemplate.vmWidth,
8281
- unit: 'mm',
8282
- },
8283
- status: 'complete',
8284
- vmBrand: vmTemplate.vmBrand,
8285
- };
8286
-
8287
- const vmDetails = await planoVmService.upsertOne(
8288
- {
8289
- 'vmName': vmInsertData.vmName,
8290
- },
8291
- vmInsertData,
8292
- );
8293
-
8294
- return {
8295
- vmId: vmDetails.toObject()._id,
8296
- startYPosition: vmTemplate.startYPosition,
8297
- endYPosition: vmTemplate.endYPosition,
8298
- xZone: vmTemplate.xZone,
8299
- };
8300
- } ) );
8301
-
8302
- const baseFixtureName = `${fixtureConfigDoc.fixtureCategory}`;
8303
- const uniqueFixtureName = await generateFixtureTemplateName( baseFixtureName, fixtureConfigDoc.fixtureWidth );
8304
-
8305
-
8306
- const fixtureTemplateData = {
8307
- ...fixtureConfigDoc,
8308
- 'shelfConfig': shelfTemplate,
8309
- 'vmConfig': vmTemplate,
8310
- 'clientId': fixtureConfigDoc.clientId,
8311
- 'fixtureName': uniqueFixtureName,
8312
- 'header': {
8313
- label: fixture.centerSubMain,
8314
- isEnabled: true,
8315
- },
8316
- 'footer': {
8317
- label: 'Storage Box',
8318
- isEnabled: true,
8319
- },
8320
- 'isBodyEnabled': true,
8321
- 'productResolutionLevel': 'L3',
8322
- 'productBrandName': [ ...fixtureProductSubBrandName ],
8323
- 'fixtureLibraryId': fixtureConfigDoc._id,
8324
- 'crestMapKey': mapKey,
8325
- };
8326
-
8327
-
8328
- delete fixtureTemplateData._id;
8329
-
8330
-
8331
- const fixtureTemplate = await fixtureConfigService.upsertOne(
8332
- { crestMapKey: mapKey },
8333
- fixtureTemplateData,
8334
- );
8335
-
8336
- const fixtureData = {
8337
- ...fixtureTemplate.toObject(),
8338
- 'storeName': layoutDoc.storeName,
8339
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
8340
- 'planoId': layoutDoc.planoId,
8341
- 'floorId': layoutDoc._id,
8342
- 'relativePosition': {
8343
- 'x': detailedXPos,
8344
- 'y': detailedYPos,
8345
- 'unit': 'ft',
8346
- },
8347
- 'fixtureNumber': fixtureCounter,
8348
- // 'relativeDetailedPosition': {
8349
- // 'x': detailedXPos,
8350
- // 'y': detailedYPos,
8351
- // 'unit': 'ft',
8352
- // },
8353
- 'associatedElementFixtureNumber': index+1,
8354
- 'fixtureConfigId': fixtureTemplate.toObject()._id,
8355
- };
8356
-
8357
- delete fixtureData._id;
8358
- delete fixtureData.shelfConfig;
8359
-
8360
- const createdFixture = await storeFixtureService.upsertOne(
8361
- {
8362
- floorId: layoutDoc._id,
8363
- fixtureNumber: fixtureCounter++,
8364
- },
8365
- fixtureData,
8366
- );
8367
-
8368
- if ( !fixtureConfigDoc.shelfConfig.length || fixture.header === 'CL' || fixture.fixtureSubname?.includes( 'CL' ) ) continue;
8369
-
8370
- fixtureTemplate.shelfConfig.forEach( async ( configShelf, j ) => {
8371
- const shelfData = {
8372
- 'clientId': '11',
8373
- 'storeName': layoutDoc.storeName,
8374
- 'storeId': storeDetails?.toObject()?.storeId ? storeDetails.toObject().storeId : 'nil',
8375
- 'planoId': layoutDoc.planoId,
8376
- 'floorId': layoutDoc._id,
8377
- 'fixtureId': createdFixture._id,
8378
- 'shelfNumber': j + 1,
8379
- 'shelfOrder': 'LTR',
8380
- 'shelfCapacity': configShelf.shelfCapacity,
8381
- 'productBrandName': configShelf.productBrandName,
8382
- 'shelfType': configShelf.shelfType,
8383
- 'productPerShelf': configShelf.productPerShelf,
8384
- 'trayRows': configShelf.trayRows,
8385
- 'productPerTray': configShelf.productPerTray,
8386
- 'zone': configShelf.zone,
8387
- };
8388
-
8389
- await fixtureShelfService.upsertOne(
8390
- {
8391
- fixtureId: createdFixture._id,
8392
- shelfNumber: j + 1,
8393
- },
8394
- shelfData,
8395
- );
8396
- } );
8397
- }
8398
-
8399
-
8400
- const now = Date.now();
8401
- const elapsedMinutes = ( now - startTime ) / 1000 / 60;
8402
- console.log( `Store name: ${storeData.storeName},Floor name: ${floorArray[floorIndex]} Iteration ${i + 1}/${storeList?.length}: total elapsed time = ${elapsedMinutes.toFixed( 2 )} minutes` );
8403
- logger.info( { functionName: 'updateCrestPlanogram', body: `Store name: ${storeData.storeName},Floor name: ${floorArray[floorIndex]} Iteration ${i + 1}/${storeList?.length}: total elapsed time = ${elapsedMinutes.toFixed( 2 )} minutes` } );
8404
- }
8405
- }
8406
-
8407
- res.sendSuccess( 'Updated Successfully' );
8408
- } catch ( e ) {
8409
- logger.error( { functionName: 'updateCrestPlanogram', error: e } );
8410
- return res.sendError( e.message || 'Internal Server Error', 500 );
8411
- }
7151
+ xlsx.writeFile( workbook, filePath );
8412
7152
  }
8413
- // function fillFeedbackFromJson( excelPath, jsonData, outputPath ) {
8414
- // const workbook = xlsx.readFile( excelPath );
8415
- // const sheetName = workbook.SheetNames[0];
8416
- // const sheet = workbook.Sheets[sheetName];
8417
-
8418
- // const data = xlsx.utils.sheet_to_json( sheet, { defval: 'Transformed by Data.Page' } );
8419
-
8420
- // const feedbackMap = {};
8421
- // jsonData.forEach( ( entry ) => {
8422
- // feedbackMap[entry.store] = entry.videoUrl;
8423
- // } );
8424
-
8425
- // const updatedData = data.map( ( row ) => {
8426
- // const store = row.storeName;
8427
- // if ( feedbackMap[store] ) {
8428
- // row.FeedBack = feedbackMap[store];
8429
- // }
8430
- // return row;
8431
- // } );
8432
-
8433
- // const newSheet = xlsx.utils.json_to_sheet( updatedData );
8434
-
8435
- // workbook.Sheets[sheetName] = newSheet;
8436
-
8437
- // xlsx.writeFile( workbook, outputPath );
8438
- // }
8439
-
8440
- // fillFeedbackFromJson('input.xlsx', feedbackJson, 'output.xlsx');
8441
-
8442
-
8443
- // function exportFixtureJsonToExcel( fixtures, filePath ) {
8444
- // const fixtureInfoArr = [];
8445
- // const shelfConfigArr = [];
8446
- // const vmConfigArr = [];
8447
-
8448
- // for ( const fixture of fixtures ) {
8449
- // fixtureInfoArr.push( {
8450
- // clientId: fixture.clientId,
8451
- // fixtureCode: fixture.fixtureCode,
8452
- // fixtureCategory: fixture.fixtureCategory,
8453
- // fixtureConfigType: fixture.fixtureConfigType,
8454
- // fixtureLength: `${fixture.fixtureLength?.value} ${fixture.fixtureLength?.unit}`,
8455
- // fixtureCapacity: fixture.fixtureCapacity,
8456
- // } );
8457
-
8458
- // ( fixture.shelfConfig || [] ).forEach( ( shelf ) => {
8459
- // shelfConfigArr.push( {
8460
- // fixtureCode: fixture.fixtureCode,
8461
- // ...shelf,
8462
- // } );
8463
- // } );
8464
-
8465
- // ( fixture.vmConfig || [] ).forEach( ( vm ) => {
8466
- // vmConfigArr.push( {
8467
- // fixtureCode: fixture.fixtureCode,
8468
- // ...vm,
8469
- // } );
8470
- // } );
8471
- // }
8472
-
8473
- // const workbook = xlsx.utils.book_new();
8474
- // xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( fixtureInfoArr ), 'Fixture Info' );
8475
- // xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( shelfConfigArr ), 'Shelf Config' );
8476
- // xlsx.utils.book_append_sheet( workbook, xlsx.utils.json_to_sheet( vmConfigArr ), 'VM Config' );
8477
-
8478
- // xlsx.writeFile( workbook, filePath );
8479
- // }
8480
7153
 
8481
7154
  // const fixtures = JSON.parse( fs.readFileSync( './input.json', 'utf-8' ) );
8482
7155
  // exportFixtureJsonToExcel( fixtures, 'output.xlsx' );