Skip to content

Commit

Permalink
Merge pull request #47 from curiosta/feat/add-product-sync
Browse files Browse the repository at this point in the history
Feat/add product sync
  • Loading branch information
Labham-Jain authored Oct 31, 2023
2 parents 5867fab + 87c8d21 commit b37c0a7
Show file tree
Hide file tree
Showing 7 changed files with 40 additions and 23 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ build
.cache

.env.*
!.env.template
!.env.template

dump.rdb
Binary file modified dump.rdb
Binary file not shown.
10 changes: 8 additions & 2 deletions src/api/routes/admin/sheets/helpers/mapSheetProduct.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Product, ProductStatus } from "@medusajs/medusa";
import { CreateProductInput } from "@medusajs/medusa/dist/types/product";
import { CreateProductInput, UpdateProductInput } from "@medusajs/medusa/dist/types/product";
import { ulid } from "ulid";


Expand All @@ -13,7 +13,12 @@ export type CreateProduct = Omit<Partial<Product>, 'variants' | 'categories'> &

export type CreateProductResponse = CreateProductInput & { id: string, rowNumber: number }

export const mapSheetProduct = (product: CreateProduct): CreateProductResponse => {
export type UpdateProductResponse = UpdateProductInput & { id: string, rowNumber: number }


export const mapSheetProduct = (product: CreateProduct): CreateProductResponse | UpdateProductResponse => {

const options = product.options?.length ? [{ id: product.options[0].id, value: 'one size' }] : undefined
return ({
id: product.id,
rowNumber: product.rowNumber,
Expand All @@ -25,6 +30,7 @@ export const mapSheetProduct = (product: CreateProduct): CreateProductResponse =
variants: [
{
title: 'one size',
options,
inventory_quantity: product.stock || 0,
prices: [
{
Expand Down
23 changes: 16 additions & 7 deletions src/api/routes/admin/sheets/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ProductStatus, authenticate } from "@medusajs/medusa"
import { ProductOption, ProductStatus, authenticate } from "@medusajs/medusa"
import express, { Router } from "express";
import CategoryService from "../../../../services/category";
import GoogleSheetAPIService, { ProductData } from "../../../../services/google-sheet-api";
Expand All @@ -7,7 +7,7 @@ import { mapSheetProduct } from "./helpers/mapSheetProduct";

type CategoriesID = { id: string }[];

type SheetProductWithCategories = ProductData & { categories: CategoriesID };
type SheetProductWithExtras = ProductData & { categories: CategoriesID, options?: ProductOption[] };

export const SheetsRouter = (router: Router) => {
router.use('/admin/sheets', express.json(), authenticate());
Expand All @@ -24,9 +24,14 @@ export const SheetsRouter = (router: Router) => {
const sheetData = await googleSheetService.getProductDataBySheetId();

const promises = sheetData.map(async (entry) => {
const location = await categoryService.getCategoryByName(entry.Location);
const location = await categoryService.getCategoryByName(entry.Location.split('/').pop().trim());
const category = await categoryService.getCategoryByName(entry.Category);

let options;
try {
const product = await productService.retrieve(entry["Product ID"], { relations: ['options'] })
options = product.options;
} catch (error) {
}
const categories: { id: string }[] = []

if (location) {
Expand All @@ -36,23 +41,27 @@ export const SheetsRouter = (router: Router) => {
categories.push({ id: category.id })
}

return { ...entry, categories }
return { ...entry, categories, options }
});

let results = (await Promise.allSettled(promises)).filter(r => r.status === 'fulfilled').map((r: any) => r.value)

results = results.map((product: SheetProductWithCategories) => {
results = results.map((product: SheetProductWithExtras) => {
return mapSheetProduct({
id: product['Product ID'],
title: product['Product title'],
description: product.Description,
stock: product.Stocks,
categories: product.categories,
rowNumber: product.rowNumber,
status: product.Draft ? ProductStatus.DRAFT : ProductStatus.PUBLISHED
status: product.Draft ? ProductStatus.DRAFT : ProductStatus.PUBLISHED,
options: product.options
})
});




const bulkAddResult = await productService.addBulkProducts(results)
const savedProductIdAndRowNumber = bulkAddResult.saved.map((p) => ({ id: p.id, rowNumber: p.rowNumber }))

Expand Down
2 changes: 0 additions & 2 deletions src/api/routes/admin/sheets/sync-categories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ export const SheetsSyncCategoriesRouter = (router: Router) => {
const googleSheetService = req.scope.resolve('googleSheetApiService') as GoogleSheetAPIService;
const categoryService = req.scope.resolve('categoryService') as CategoryService;

console.log('\n\n\n\n', process.env, '\n\n\n\n');

if (typeof req.query.sheetId === 'string') {
googleSheetService.sheetId = req.query.sheetId
}
Expand Down
1 change: 1 addition & 0 deletions src/services/category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class CategoryService extends ProductCategoryService {
super(container)
}
async retrieveAllCategoriesName() {

const retrieveAllCategories = `
SELECT name FROM product_category WHERE handle NOT LIKE 'loc:%'
`
Expand Down
23 changes: 12 additions & 11 deletions src/services/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ class ProductService extends BaseProductService {

async addBulkProducts(products: ((CreateProductInput | UpdateProductInput) & { id: string; rowNumber: number; })[]) {
await this.loginAdmin();

const promises = products.map((product, i) => {
return new Promise<Partial<Product & { rowNumber: number }>>(async (resolve, reject) => {
if (product.id) {
Expand All @@ -77,18 +76,21 @@ class ProductService extends BaseProductService {
} catch (error) {
productExists = false;
}
try {
if (productExists) {
const { id, rowNumber, ...updateProduct } = product as UpdateProductInput & { id: string; rowNumber: number; };
const { product: updatedProduct } = await this.updateProductWithFetch(id, updateProduct)
resolve({ ...updatedProduct, rowNumber });
} else {

if (productExists) {
const { id, rowNumber, ...updateProduct } = product as UpdateProductInput & { id: string; rowNumber: number; };
const { product: updatedProduct } = await this.updateProductWithFetch(id, updateProduct)
resolve({ ...updatedProduct, rowNumber });
} else {

const { id, rowNumber, ...createProduct } = product as CreateProductInput & { id: string; rowNumber: number; }
const { id, rowNumber, ...createProduct } = product as CreateProductInput & { id: string; rowNumber: number; }

const { product: createdProduct } = await this.createProductWithFetch(createProduct);
const { product: createdProduct } = await this.createProductWithFetch(createProduct);

resolve({ ...createdProduct, rowNumber })
resolve({ ...createdProduct, rowNumber })
}
} catch (error) {
console.log('An error occurred!', error.response.data);
}
} else {
const { id, rowNumber, ...createProduct } = product as CreateProductInput & { id: string, rowNumber: number; }
Expand All @@ -112,7 +114,6 @@ class ProductService extends BaseProductService {
}

} catch (error) {
console.log(error);
}
}
}
Expand Down

0 comments on commit b37c0a7

Please sign in to comment.