import moment, { Moment } from "moment"; import { Strapi } from "@strapi/strapi"; import { OrderType, CheckoutFragmentFragment } from "./dutchieGraphql/sdk"; import { dutchieClient } from "./dutchieGraphql/client"; import { extractErrorMessage } from "./apiHelper"; export interface SanitizedProfile { id: number; firstName: string | null; lastName: string | null; latitude: number | null; longitude: number | null; zipcode: string | null; orderType: "PICKUP" | "DELIVERY" | null; createdAt: Moment; updatedAt: Moment; mobilePhone: string | null; birthDate: Moment | null; medicalCardNumber: string | null; medicalCardExpirationDate: Moment | null; medicalCardState: string | null; street1: string | null; street2: string | null; city: string | null; state: string; } export default ({ strapi }: { strapi: Strapi }) => { const exportServices = { checkoutReturnValue( sequence: number | undefined, redirectUrl: string | null, checkoutFragment: CheckoutFragmentFragment ) { const rv = { sequence, redirectUrl, checkoutId: checkoutFragment.id, priceSummary: { subtotal: checkoutFragment.priceSummary.subtotal, taxes: checkoutFragment.priceSummary.taxes, total: checkoutFragment.priceSummary.total, fees: checkoutFragment.priceSummary.fees, discounts: checkoutFragment.priceSummary.discounts, }, items: checkoutFragment.items.map((item) => ({ itemId: item.id, productERPId: item.productId, quantity: item.quantity, valid: item.valid, isDiscounted: item.isDiscounted, basePrice: item.basePrice, discounts: item.discounts?.total || 0, option: item.option, })), }; return rv; }, async create( { retailerId, orderType, pricingType, items, sequence, postCheckoutUrl }, context ) { const publicDutchieClient = dutchieClient(); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); if (retailer) { let profile: SanitizedProfile | null = null; /* // NO profile for now const { user } = context.state; if (user) { profile = await strapi .service("api::profile.profile") .findOneAndSanitize(user); } else { profile = null; } */ const address = profile ? { zip: profile.zipcode || "", street1: profile.street1 || "", street2: profile.street2 || "", city: profile.city || "", state: profile.state || "", } : undefined; const resp = await publicDutchieClient.CreateCheckout({ retailerId: retailer.ERPId, orderType, pricingType, address: orderType === OrderType.Delivery ? address : undefined, }); const checkoutFragment = resp.data?.createCheckout; const checkoutId = checkoutFragment?.id; if (checkoutId) { const itemQueries = items.map((item) => publicDutchieClient.AddItemToCheckout({ checkoutId, option: item.option, productId: item.productERPId, retailerId: retailer.ERPId, quantity: item.quantity, }) ); try { await Promise.all(itemQueries); } catch (e) { const errorMsg = extractErrorMessage(e.message); if (errorMsg === "Not Found") { throw new Error("Product out of stock"); } throw new Error(errorMsg); } const checkoutResp = await publicDutchieClient.Checkout({ retailerId: retailer.ERPId, id: checkoutId, }); let redirectUrl = checkoutResp.data?.checkout?.redirectUrl || ""; const queryParams: any = { r: postCheckoutUrl, }; if (profile) { if (profile.firstName?.length) { queryParams.firstName = profile.firstName; } if (profile.lastName?.length) { queryParams.lastName = profile.lastName; } if (profile.mobilePhone?.length) { queryParams.phone = profile.mobilePhone.slice(-10); } if (profile.birthDate) { queryParams.birthdate = profile.birthDate.format("MMDDYYYY"); } if (profile.medicalCardNumber?.length) { queryParams.medCardNumber = profile.medicalCardNumber; } if (profile.medicalCardExpirationDate) { queryParams.medCardExpiration = profile.medicalCardExpirationDate.format("MM-DD-YYYY"); } if (profile.medicalCardState?.length) { queryParams.medCardState = profile.medicalCardState; } } const queryString = Object.keys(queryParams) .map((key) => { return `${encodeURIComponent(key)}=${encodeURIComponent( queryParams[key] )}`; }) .join("&"); redirectUrl += `?${queryString}`; return exportServices.checkoutReturnValue( sequence, redirectUrl, checkoutResp.data.checkout ); } else { throw new Error(`Unable to create checkout, ${retailerId} ${items}`); } } else { throw new Error(`Retailer not found with id ${retailerId}`); } }, async fetch({ retailerId, checkoutId, redirectUrl }) { const publicDutchieClient = dutchieClient(); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); const checkoutResp = await publicDutchieClient.Checkout({ retailerId: retailer.ERPId, id: checkoutId, }); const checkoutFragment = checkoutResp.data?.checkout; if (checkoutFragment) { return exportServices.checkoutReturnValue( 0, redirectUrl, checkoutFragment ); } else { throw new Error( `Unable to fetch checkout, ${retailerId} ${checkoutId}` ); } }, async addItem({ retailerId, checkoutId, item, sequence }) { const publicDutchieClient = dutchieClient(); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); let checkoutResp; try { checkoutResp = await publicDutchieClient.AddItemToCheckout({ checkoutId, option: item.option, productId: item.productERPId, retailerId: retailer.ERPId, quantity: item.quantity, }); } catch (e) { const errorMsg = extractErrorMessage(e.message); if (errorMsg === "Not Found") { throw new Error("Product out of stock"); } throw new Error(errorMsg); } if (checkoutResp.data?.addItem) { return exportServices.checkoutReturnValue( sequence, null, checkoutResp.data.addItem ); } else { throw new Error( `Unable to add item, ${retailerId} ${checkoutId} ${item}` ); } }, async removeItem({ retailerId, checkoutId, itemId, sequence }) { const publicDutchieClient = dutchieClient(); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); const checkoutResp = await publicDutchieClient.RemoveItemFromCheckout({ checkoutId, retailerId: retailer.ERPId, itemId, }); if (checkoutResp.data?.removeItem) { return exportServices.checkoutReturnValue( sequence, null, checkoutResp.data.removeItem ); } else { throw new Error( `Unable to remove item, ${retailerId} ${checkoutId} ${itemId}` ); } }, async updateQuantity({ retailerId, checkoutId, itemId, quantity, sequence, }) { const publicDutchieClient = dutchieClient(); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); let checkoutResp; try { checkoutResp = await publicDutchieClient.UpdateQuantityFromCheckout({ checkoutId, retailerId: retailer.ERPId, itemId, quantity, }); } catch (e) { const errorMsg = extractErrorMessage(e.message); throw new Error(errorMsg); } if (checkoutResp.data?.updateQuantity) { return exportServices.checkoutReturnValue( sequence, null, checkoutResp.data.updateQuantity ); } else { throw new Error( `Unable to remove item, ${retailerId} ${checkoutId} ${itemId}` ); } }, async fetchOrderByNumber(retailerId: string, orderNumber: string) { const privateDutchieClient = dutchieClient(false); const resp = await privateDutchieClient.orderByNumber({ retailerId, orderNumber, }); if (resp.data?.orders?.length) { return resp.data?.orders[0]; } else { throw new Error(`No order found with orderNumber: ${orderNumber}`); } }, async fetchOrderById({ retailerId, orderNumber }) { const privateDutchieClient = dutchieClient(false); const retailer = await strapi.entityService.findOne( "plugin::dutchie-plus.retailer", retailerId ); try { const resp = await privateDutchieClient.orderByNumber({ retailerId: retailer.ERPId, orderNumber, }); return resp.data?.orders[0]; } catch (e) { console.error(e); return null; } }, }; return exportServices; };