import { Strapi } from "@strapi/strapi"; import { dutchieClient } from "./dutchieGraphql/client"; import { Client } from "@googlemaps/google-maps-services-js"; import { getConfig } from "../config"; import { MenuType } from "./dutchieGraphql/sdk"; const apiName = "plugin::dutchie-plus.retailer"; async function fetchAddressInfo(address: string, client: Client, key: string) { if (!key) { return {}; } const resp = await client.geocode({ params: { address: address, key, }, }); const [result] = resp.data.results; const street: string[] = []; let city = ""; let state = ""; let zipcode = ""; let endOfStreet = false; for (const component of result.address_components) { for (const type of component.types) { if (type === "political") { endOfStreet = true; } if (type === "locality") { city = component.long_name; } if (type === "administrative_area_level_1") { state = component.short_name; } if (type === "postal_code") { zipcode = component.long_name; } } if (!endOfStreet) { street.push(component.short_name); } } return { street: street.join(" "), city, state, zipcode, latitude: result.geometry.location.lat, longitude: result.geometry.location.lng, }; } export default ({ strapi }: { strapi: Strapi }) => { const googleMapsApiKey = getConfig(strapi, "googleMapsApiKey"); const retailerAddressFilter = getConfig(strapi, "retailerAddressFilter"); const testRetailerName = getConfig(strapi, "testRetailerName"); const exportServices = { async findAllRetailers(publicationState = "preview") { let retailerRecords: any[] = []; const limit = 100; let start = 0; while (true) { const records = await strapi.entityService.findMany(apiName, { publicationState, limit, start, orderBy: "id", }); if (records && records.length > 0) { retailerRecords = [...retailerRecords, ...records]; if (records.length < limit) { break; } } else { break; } start += limit; } return retailerRecords; }, async dutchieFetchRetailersAndFilter() { const publicDutchieClient = dutchieClient(); const resp = await publicDutchieClient.fetchRetailers(); let retailers = resp?.data?.retailers || []; if (retailerAddressFilter) { const re = new RegExp(retailerAddressFilter); retailers = retailers.filter( (retailer) => retailer.name === testRetailerName || retailer.address.match(re) ); } return retailers; }, async syncRetailers() { const retailers = await exportServices.dutchieFetchRetailersAndFilter(); const rv = { match: 0, inserted: 0, deprecated: 0, published: 0, draft: 0, }; const dutchieRetailers = {}; const client = new Client({}); if (retailers && retailers.length > 0) { const retailerRecords = await exportServices.findAllRetailers(); retailers.forEach((retailer) => { dutchieRetailers[retailer.id] = retailer; }); const localRetailers: { [key: string]: any } = {}; retailerRecords.forEach((retailerRecord) => { localRetailers[retailerRecord.ERPId] = retailerRecord; }); for (const retailer of retailers) { let customerType = "Both"; if (retailer.menuTypes.length === 1) { const [menuType] = retailer.menuTypes; if (menuType === MenuType.Medical) { customerType = "Medical"; } else { customerType = "Recreational"; } } if (localRetailers[retailer.id]) { rv.match += 1; if (localRetailers[retailer.id].publishedAt) { rv.published += 1; } else { rv.draft += 1; } const payload = { hours: retailer.hours, customerType, }; if (!localRetailers[retailer.id].latitude) { Object.assign( payload, await fetchAddressInfo( retailer.address, client, googleMapsApiKey ) ); } await strapi.entityService.update( apiName, localRetailers[retailer.id].id, { data: payload, } ); } else { const slug = await strapi .service("plugin::content-manager.uid") .generateUIDField({ contentTypeUID: apiName, field: "slug", data: { name: retailer.name, }, }); const payload = await fetchAddressInfo( retailer.address, client, googleMapsApiKey ); const newRetailer = await strapi.entityService.create(apiName, { data: { ERPId: retailer.id, publishedAt: null, name: retailer.name, slug, hours: retailer.hours, customerType, ...payload, }, }); //eslint-disable-next-line require-atomic-updates localRetailers[retailer.id] = newRetailer; rv.inserted += 1; rv.draft += 1; } const localRetailer = localRetailers[retailer.id]; await strapi .plugin("dutchie-plus") .service("special") .syncRetailer(localRetailer); } for (const retailerRecord of retailerRecords) { if ( !dutchieRetailers[retailerRecord.ERPId] && retailerRecord.publishedAt ) { // await strapi.entityService.update(apiName, retailerRecord.id, { // data: { publishedAt: null }, // }); rv.deprecated += 1; rv.draft += 1; } } } const successResp = { success: true, message: [ `Matching existed: ${rv.match}`, `Inserted new: ${rv.inserted}`, `Unpublished non-Dutchie retailers: ${rv.deprecated}`, `Total published: ${rv.published}`, `Total draft: ${rv.draft}`, ], }; return successResp; }, graphqlFindNearby: async (args) => { const { latitude, longitude } = args; const retailersResp = await dutchieClient().retailersNearLocation({ latitude, longitude, }); const retailerERPIds: string[] = []; for (const dutchieRetailer of retailersResp.data.retailersNearLocation) { if (dutchieRetailer.locationDetail.validForDelivery) { retailerERPIds.push(dutchieRetailer.retailer.id); } } let retailers = []; if (retailerERPIds.length > 0) { // fetch all retailers with ERPId in retailerERPIds retailers = await strapi.entityService.findMany(apiName, { filters: { ERPId: { $in: retailerERPIds, }, }, }); } return retailers; }, }; return exportServices; };