import { Strapi } from "@strapi/strapi"; import { ProductFragmentFragment, MenuType } from "./dutchieGraphql/sdk"; import { uniqBy } from "lodash"; import { getConfig } from "../config"; import { extractErrorMessage, fetchAllDutchieProducts, fetchAllDutchieSpecialProductIds, } from "./apiHelper"; const apiName = "plugin::dutchie-plus.inventory"; type EntitiesByKey = { [key: string]: any }; type FilterByCategory = { subcategory: { [key: string]: { displayName: string; count: number; }; }; strainType: { [key: string]: { displayName: string; count: number; }; }; brand: { [key: string]: { displayName: string; count: number; }; }; weight: { [key: string]: { displayName: string; count: number; }; }; discount: { [key: string]: { displayName: string; count: number; }; }; }; export default ({ strapi }: { strapi: Strapi }) => { const autoPublishProducts = getConfig(strapi, "autoPublishProducts"); const exportServices = { async allEntitiesByKey( contentType: string, key: string, options: any = {} ) { const entitiesByKey: EntitiesByKey = {}; let startId = 0; const resourceName = `plugin::dutchie-plus.${contentType}`; while (true) { const entities = await strapi.entityService.findMany(resourceName, { ...options, limit: 1000, orderBy: "id", start: startId, }); for (const entity of entities) { entitiesByKey[entity[key]] = entity; } if (entities.length < 1000) { break; } startId += 1000; } return entitiesByKey; }, async findOrCreate( contentType: string, dutchieValue: string | undefined, localEntities: EntitiesByKey ) { const resourceName = `plugin::dutchie-plus.${contentType}`; let entity: any = null; if (dutchieValue) { if (!localEntities[dutchieValue]) { const slug = await strapi .service("plugin::content-manager.uid") .generateUIDField({ contentTypeUID: resourceName, field: "slug", data: { name: dutchieValue, }, }); entity = await strapi.entityService.create(resourceName, { data: { name: dutchieValue, displayName: dutchieValue, slug, }, }); //eslint-disable-next-line require-atomic-updates localEntities[dutchieValue] = entity; return { entity, isNew: true, }; } else { entity = localEntities[dutchieValue]; } } return { entity, isNew: false, }; }, async cleanupStaleInventories() { const staleInventories = await strapi.entityService.findMany( "plugin::dutchie-plus.inventory", { filters: { retailer: null, }, } ); for (const inventory of staleInventories) { await strapi.entityService.delete( "plugin::dutchie-plus.inventory", inventory.id ); } console.log("Delete staleInventories", staleInventories.length); }, async syncRetailer({ id }) { const retailerId = parseInt(id); const lockAquired = await strapi .plugin("dutchie-plus") .service("mutexLock") .aquireRetailerLock(retailerId); if (!lockAquired) { return { error: "Another sync in progress" }; } const rv = { medical: { new: 0, match: 0, oos: 0, }, recreational: { new: 0, match: 0, oos: 0, }, both: { new: 0, match: 0, oos: 0, }, products: { new: 0, match: 0, oos: 0, }, brands: { new: 0, match: 0, }, categories: { new: 0, match: 0, }, subcategories: { new: 0, match: 0, }, strainTypes: { new: 0, match: 0, }, terpenes: { new: 0, match: 0, }, }; try { let retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", id, { populate: ["specials"], } ); const filter: { [categoryName: string]: FilterByCategory } = {}; let dutchieMedicalProductList: ProductFragmentFragment[] = []; try { dutchieMedicalProductList = await fetchAllDutchieProducts( retailer.ERPId, MenuType.Medical ); } catch (e: any) { const error = extractErrorMessage(e.message); throw new Error(error); } let dutchieRecreationalProductList: ProductFragmentFragment[] = []; try { dutchieRecreationalProductList = await fetchAllDutchieProducts( retailer.ERPId, MenuType.Recreational ); } catch (e: any) { const error = extractErrorMessage(e.message); throw new Error(error); } const medicalAndRecreationalProductList = uniqBy( [...dutchieMedicalProductList, ...dutchieRecreationalProductList], ({ id }) => id ); const localSpecials = await exportServices.allEntitiesByKey( "special", "id", { filters: { retailer: retailer.id, }, } ); const inventoryERPIdMapSpecials: { [key: string]: any[] } = {}; for (const localSpecial of Object.values(localSpecials)) { const dutchieSpeicalProductList = await fetchAllDutchieSpecialProductIds( retailer.ERPId, localSpecial.ERPId ); for (const ERPId of dutchieSpeicalProductList) { if (!inventoryERPIdMapSpecials[ERPId]) { inventoryERPIdMapSpecials[ERPId] = []; } inventoryERPIdMapSpecials[ERPId].push(localSpecial); } } const localInventories = await exportServices.allEntitiesByKey( "inventory", "productERPId", { publicationState: "preview", filters: { retailer: retailer.id, }, populate: { product: { fields: ["id", "ERPId"], }, activeTerpenes: { populate: ["terpene"], }, specials: { fields: ["id"], }, }, } ); const localBrands = await exportServices.allEntitiesByKey( "brand", "name" ); const localCategory = await exportServices.allEntitiesByKey( "category", "name" ); const localSubcategory = await exportServices.allEntitiesByKey( "subcategory", "name" ); const localStraintype = await exportServices.allEntitiesByKey( "strain-type", "name" ); const localTerpenes = await exportServices.allEntitiesByKey( "terpene", "name" ); const retailerHasBrands = new Set(); const retailerHasCategory = new Set(); const retailerHasStrainType = new Set(); const dutchieProducts: { [key: string]: ProductFragmentFragment } = {}; if (medicalAndRecreationalProductList.length > 0) { const ERPIds = medicalAndRecreationalProductList.map( (dutchieItem) => dutchieItem.posId ); const localProducts = await exportServices.allEntitiesByKey( "product", "ERPId", { filters: { ERPId: { $in: ERPIds, }, }, } ); for (const dutchieProduct of medicalAndRecreationalProductList) { if (!dutchieProduct.posId) { continue; } dutchieProducts[dutchieProduct.posId] = dutchieProduct; const categoryEntity = await exportServices.findOrCreate( "category", dutchieProduct.category, localCategory ); if (categoryEntity.isNew) { rv.categories.new += 1; } else { rv.categories.match += 1; } if (!filter[categoryEntity.entity?.name]) { filter[categoryEntity.entity.name] = { subcategory: {}, strainType: {}, brand: {}, weight: {}, discount: { saleRec: { displayName: "Sale", count: 0, }, saleMed: { displayName: "Sale", count: 0, }, specialRec: { displayName: "Special", count: 0, }, specialMed: { displayName: "Special", count: 0, }, }, }; } const filterByCategory = filter[categoryEntity.entity.name]; const subcategoryEntity = await exportServices.findOrCreate( "subcategory", dutchieProduct.subcategory, localSubcategory ); if (subcategoryEntity.isNew) { rv.subcategories.new += 1; } else { rv.subcategories.match += 1; } if (filterByCategory && subcategoryEntity.entity) { if ( !filterByCategory.subcategory[subcategoryEntity.entity.name] ) { filterByCategory.subcategory[subcategoryEntity.entity.name] = { displayName: subcategoryEntity.entity.displayName, count: 1, }; } else { filterByCategory.subcategory[ subcategoryEntity.entity.name ].count += 1; } } const strainTypeEntity = await exportServices.findOrCreate( "strain-type", dutchieProduct.strainType, localStraintype ); if (strainTypeEntity.isNew) { rv.strainTypes.new += 1; } else { rv.strainTypes.match += 1; } if (filterByCategory && strainTypeEntity.entity) { if (!filterByCategory.strainType[strainTypeEntity.entity.name]) { filterByCategory.strainType[strainTypeEntity.entity.name] = { displayName: strainTypeEntity.entity.displayName, count: 1, }; } else { filterByCategory.strainType[ strainTypeEntity.entity.name ].count += 1; } } const brandEntity = await exportServices.findOrCreate( "brand", dutchieProduct.brand?.name, localBrands ); if (brandEntity.isNew) { rv.brands.new += 1; } else { rv.brands.match += 1; } if (filterByCategory && brandEntity.entity) { if (!filterByCategory.brand[brandEntity.entity.name]) { filterByCategory.brand[brandEntity.entity.name] = { displayName: brandEntity.entity.displayName, count: 1, }; } else { filterByCategory.brand[brandEntity.entity.name].count += 1; } } for (const varaint of dutchieProduct.variants) { const weight = varaint.option; if (filterByCategory.weight[weight]) { filterByCategory.weight[weight].count += 1; } else { filterByCategory.weight[weight] = { displayName: weight, count: 1, }; } } const activeTerpenes: any[] = []; if (dutchieProduct.terpenes?.length) { for (const dutchieTerpene of dutchieProduct.terpenes) { if ( dutchieTerpene?.value === null || dutchieTerpene?.value === undefined || dutchieTerpene.value < 0 ) { continue; } const name = dutchieTerpene?.terpene?.name; if (name) { let terpene = null; if (!localTerpenes[name]) { terpene = await strapi.entityService.create( "plugin::dutchie-plus.terpene", { data: { name: name, displayName: name, description: dutchieTerpene.terpene?.potentialHealthBenefits?.join( ", " ), }, } ); //eslint-disable-next-line require-atomic-updates localTerpenes[name] = terpene; rv.terpenes.new += 1; } else { terpene = localTerpenes[name]; rv.terpenes.match += 1; } activeTerpenes.push({ terpene, value: dutchieTerpene.value, unit: dutchieTerpene.unit, }); } } } let localProduct: any = null; if (localProducts[dutchieProduct.posId]) { localProduct = localProducts[dutchieProduct.posId]; rv.products.match += 1; if (localProduct.publishedAt) { if (brandEntity.entity) { retailerHasBrands.add(brandEntity.entity); } if (categoryEntity.entity) { retailerHasCategory.add(categoryEntity.entity); } if (strainTypeEntity.entity) { retailerHasStrainType.add(strainTypeEntity.entity); } } const data = {}; for (const effect of dutchieProduct.effects) { if ( typeof localProduct[effect.toLocaleLowerCase()] !== "boolean" ) { data[effect.toLocaleLowerCase()] = true; } } if (Object.keys(data).length) { await strapi.entityService.update( "plugin::dutchie-plus.product", localProduct.id, { data, } ); } } else { const slug = await strapi .service("plugin::content-manager.uid") .generateUIDField({ contentTypeUID: "plugin::dutchie-plus.product", field: "slug", data: { name: dutchieProduct.name, }, }); const payload = { ERPId: dutchieProduct.posId, name: dutchieProduct.name, description: dutchieProduct.description, brand: brandEntity.entity, category: categoryEntity.entity, subcategory: subcategoryEntity.entity, strainType: strainTypeEntity.entity, slug, publishedAt: autoPublishProducts ? new Date() : null, image: null, stockImageUrl: dutchieProduct.image, }; for (const effect of dutchieProduct.effects) { payload[effect.toLocaleLowerCase()] = true; } localProduct = await strapi.entityService.create( "plugin::dutchie-plus.product", { data: payload, } ); //eslint-disable-next-line require-atomic-updates localProducts[dutchieProduct.posId] = localProduct; rv.products.new += 1; } let inventoryMenuType = "BOTH"; let rvEntry = rv.both; const isMedicalProduct = dutchieMedicalProductList.findIndex( (p) => p.id === dutchieProduct.id ) !== -1; const isRecreationalProduct = dutchieRecreationalProductList.findIndex( (p) => p.id === dutchieProduct.id ) !== -1; if (isMedicalProduct && isRecreationalProduct) { inventoryMenuType = "BOTH"; } else if (isMedicalProduct) { inventoryMenuType = "MEDICAL"; rvEntry = rv.medical; } else { inventoryMenuType = "RECREATIONAL"; rvEntry = rv.recreational; } let isSpecialRec = false; let isSpecialMed = false; const specialIds = ( inventoryERPIdMapSpecials[dutchieProduct.id] || [] ) .map((localSpecial) => { if (localSpecial.type === "OFFER") { if (localSpecial.menuType === "MEDICAL") { isSpecialMed = true; } if (localSpecial.menuType === "RECREATIONAL") { isSpecialRec = true; } if (localSpecial.menuType === "BOTH") { isSpecialMed = true; isSpecialRec = true; } } return localSpecial.id; }) .sort(); const weights = []; let lowestPrice = 100000000; let isOnSaleRec = false; let isOnSaleMed = false; for (const variant of dutchieProduct.variants) { let prices = [ variant.priceMed, variant.priceRec, variant.specialPriceMed, variant.specialPriceRec, ].filter((p) => p); lowestPrice = Math.min(lowestPrice, ...prices); if ( variant.specialPriceMed && variant.specialPriceMed < variant.priceMed ) { isOnSaleMed = true; } if ( variant.specialPriceRec && variant.specialPriceRec < variant.priceRec ) { isOnSaleRec = true; } weights.push(variant.option); } if (isOnSaleMed) { filter[categoryEntity.entity.name].discount.saleMed.count += 1; } if (isOnSaleRec) { filter[categoryEntity.entity.name].discount.saleRec.count += 1; } if (isSpecialMed) { filter[categoryEntity.entity.name].discount.specialMed.count += 1; } if (isSpecialRec) { filter[categoryEntity.entity.name].discount.specialRec.count += 1; } const sharedInventoryPayload = { cbdFormatted: dutchieProduct.potencyCbd?.formatted || "", thcFormatted: dutchieProduct.potencyThc?.formatted || "", staffPick: dutchieProduct.staffPick, inventoryMenuType, lowestPrice, isOnSaleRec, isOnSaleMed, isSpecialRec, isSpecialMed, }; if (localInventories[dutchieProduct.id]) { rvEntry.match += 1; let isInventorySame = true; const localInventory = localInventories[dutchieProduct.id]; // if ( // localInventory.activeTerpenes.length !== activeTerpenes.length // ) { // isInventorySame = false; // } // for (const oneActive of activeTerpenes) { // const localActive = localInventory.activeTerpenes.find( // (oneTerpene) => oneTerpene.terpene.id === oneActive.terpene.id // ); // if (localActive) { // oneActive.id = localActive.id; // if ( // oneActive.unit !== localActive.unit || // oneActive.value !== localActive.value // ) { // isInventorySame = false; // } // } else { // isInventorySame = false; // } // } for (const [key, value] of Object.entries( sharedInventoryPayload )) { if (localInventory[key] !== value) { isInventorySame = false; break; } } if ( !localInventory.variants || JSON.stringify(localInventory.variants) !== JSON.stringify(dutchieProduct.variants) ) { isInventorySame = false; } const existingSpecialIds = (localInventory.specials || []) .map((special) => special.id) .sort(); let needUpdateSpecials = false; if ( JSON.stringify(existingSpecialIds) !== JSON.stringify(specialIds) ) { isInventorySame = false; needUpdateSpecials = true; } if (!isInventorySame) { await strapi.entityService.update(apiName, localInventory.id, { data: { variants: dutchieProduct.variants, weights, ...sharedInventoryPayload, //activeTerpenes, ...(needUpdateSpecials ? { specials: inventoryERPIdMapSpecials[dutchieProduct.id], } : {}), ERPSyncedAt: new Date(), }, }); } delete localInventories[dutchieProduct.id]; } else { try { await strapi.entityService.create(apiName, { data: { retailer, weights, productERPId: dutchieProduct.id, product: localProducts[dutchieProduct.posId], ERPSyncedAt: new Date(), publishedAt: new Date(), specials: inventoryERPIdMapSpecials[dutchieProduct.id], variants: dutchieProduct.variants, // activeTerpenes, ...sharedInventoryPayload, }, }); } catch (error: any) { console.error(error, dutchieProduct); } rvEntry.new += 1; } } } for (const inventory of Object.values(localInventories)) { await strapi.entityService.delete(apiName, inventory.id); switch (inventory.inventoryMenuType) { case "RECREATIONAL": { rv.recreational.oos += 1; break; } case "MEDICAL": { rv.medical.oos += 1; break; } default: { rv.both.oos += 1; } } } await strapi.entityService.update( "plugin::dutchie-plus.retailer", retailerId, { data: { ERPSyncedAt: new Date(), brands: Array.from(retailerHasBrands), categories: Array.from(retailerHasCategory), strainTypes: Array.from(retailerHasStrainType), filter, }, } ); await strapi .plugin("dutchie-plus") .service("meilisearch") .syncRetailer({ id: retailer.id }); await strapi .plugin("dutchie-plus") .service("mutexLock") .releaseRetailerLock(retailerId); } catch (e: any) { await strapi .plugin("dutchie-plus") .service("mutexLock") .releaseRetailerLock(retailerId); throw e; } return { data: rv, }; }, }; return exportServices; };