From f2b2320df596c382524b3478b4491a32e1600981 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Mar 2023 11:19:10 +0700 Subject: [PATCH] Implemented with mayar.id --- package.json | 5 +- src/hooks.server.ts | 7 +- src/lib/Nav.svelte | 12 +- src/lib/components/Pricesummary.svelte | 19 +- src/lib/config/index.ts | 5 +- src/lib/server/cart.ts | 27 ++- src/lib/services/CartService.ts | 114 ++++------ src/lib/services/CategoryService.ts | 18 +- src/lib/services/HomeService.ts | 31 +-- src/lib/services/ProductService.ts | 207 +++++++++++------- src/lib/types.d.ts | 119 ++++++++++ src/lib/utils/generateUUID.ts | 12 + src/lib/utils/index.ts | 2 +- src/lib/utils/server.ts | 47 ++++ src/routes/(app)/+page.server.ts | 22 +- src/routes/(app)/+page.svelte | 106 +++++++-- .../(app)/auth/otp-login/+page.server.ts | 1 + src/routes/(app)/cart/+page.server.ts | 103 ++++----- src/routes/(app)/cart/+page.svelte | 36 +-- src/routes/(app)/categories/+page.svelte | 2 +- .../(catalog)/product/[slug]/+page.server.ts | 3 +- .../(catalog)/product/[slug]/+page.svelte | 189 ++++++---------- src/routes/server/cart/+server.ts | 1 + src/routes/server/store/+server.ts | 69 +++--- static/favicon-old.ico | Bin 0 -> 3758 bytes static/favicon.ico | Bin 3758 -> 15406 bytes 26 files changed, 687 insertions(+), 470 deletions(-) create mode 100644 src/lib/utils/generateUUID.ts create mode 100644 static/favicon-old.ico diff --git a/package.json b/package.json index 0f6abc26..d0f53792 100644 --- a/package.json +++ b/package.json @@ -73,5 +73,8 @@ "zod": "3.20.6", "zod-form-data": "1.3.1" }, - "type": "module" + "type": "module", + "dependencies": { + "svelte-paginate": "0.1.0" + } } diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 824bd8ac..f34e1720 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -33,9 +33,10 @@ export const handle: Handle = async ({ event, resolve }) => { event.locals.isDesktop = isDesktop const isShowBackButton = !listOfPagesWithoutBackButton.includes(url?.pathname) event.locals.isShowBackButton = isShowBackButton - event.locals.store = await fetchStoreData(event) - event.locals.me = await authenticateUser(event) + // event.locals.store = await fetchStoreData(event) + // event.locals.me = await authenticateUser(event) event.locals.cart = await fetchCart(event) + // Bellow conversion is for medusajs // const derivedSid: string = event.cookies.get('connect.sid') || '' // event.locals.sid = derivedSid @@ -43,7 +44,7 @@ export const handle: Handle = async ({ event, resolve }) => { // event.request.headers.delete('connection') return await resolve(event) } catch (e) { - const err = `Store Not Found @Hook + const err = `Store Not Found @Hook
ID: ${event.locals.store?.id}
ORIGIN: ${event.locals?.origin}
DOMAIN(env): ${DOMAIN} diff --git a/src/lib/Nav.svelte b/src/lib/Nav.svelte index c07b5ab1..1fd92e8d 100644 --- a/src/lib/Nav.svelte +++ b/src/lib/Nav.svelte @@ -369,7 +369,7 @@ async function onSearchSubmit({ detail }) { {/if} {#if me?.active} - + --> - + --> {:else} - - + --> {/if} diff --git a/src/lib/components/Pricesummary.svelte b/src/lib/components/Pricesummary.svelte index 908983ae..ef1b4413 100644 --- a/src/lib/components/Pricesummary.svelte +++ b/src/lib/components/Pricesummary.svelte @@ -42,7 +42,12 @@ function submit() {

Total

-

{cart.formattedAmount?.subtotal || '-'}

+

+ {cart.total.toLocaleString('id-ID', { + style: 'currency', + currency: 'IDR' + }) || '-'} +

{#if cart?.savings > 0} @@ -109,7 +114,8 @@ function submit() { class="group w-full uppercase" loading="{loading}" disabled="{disabled}" - on:click="{() => goto(`${nextpage}`)}"> + on:click="{() => + (window.location.href = `https://www.mayar.shop/checkout/cart/${cart?.cartId}`)}"> {text} {#if showNextIcon} @@ -131,7 +137,8 @@ function submit() { class="w-full uppercase" loading="{loading}" disabled="{disabled}" - on:click="{submit}"> + on:click="{() => + (window.location.href = `https://www.mayar.shop/checkout/cart/${cart?.cartId}`)}"> {text} {#if showNextIcon} @@ -159,7 +166,8 @@ function submit() { class="w-full uppercase" loading="{loading}" disabled="{disabled}" - on:click="{() => goto(`${nextpage}`)}"> + on:click="{() => + (window.location.href = `https://www.mayar.shop/checkout/cart/${cart?.cartId}`)}"> {text} {#if showNextIcon} @@ -182,7 +190,8 @@ function submit() { class="w-full uppercase" loading="{loading}" disabled="{disabled}" - on:click="{submit}"> + on:click="{() => + (window.location.href = `https://www.mayar.shop/checkout/cart/${cart?.cartId}`)}"> {text} {#if showNextIcon} diff --git a/src/lib/config/index.ts b/src/lib/config/index.ts index 7825f0b5..8666380a 100644 --- a/src/lib/config/index.ts +++ b/src/lib/config/index.ts @@ -17,9 +17,9 @@ export const loginUrl = '/auth/login' export const weightUnit = 'g' export const currencyCode = 'USD' export const currencySymbol = '$' -export const DOMAIN = env.PUBLIC_DOMAIN || 'demo.litekart.in' +export const DOMAIN = env.PUBLIC_DOMAIN || 'http://localhost:3000' export const entity = 'Misiki' -export const HTTP_ENDPOINT = env.PUBLIC_HTTP_ENDPOINT || 'https://api.litekart.in' +export const HTTP_ENDPOINT = env.PUBLIC_HTTP_ENDPOINT || 'https://api.mayar.club' export const IMAGE_CDN_URL = 'https://ik.imagekit.io/3wzatecz51w3i' export const mediaqueries = { xs: '(min-width: 480px)', @@ -47,6 +47,7 @@ export const sorts = [ { name: `Name: Asc`, val: 'name' }, { name: `Name: Desc`, val: '-name' } // { name: 'Most Viewed', val: '-views' } ] +export const logo = 'https://framerusercontent.com/images/0aaSOxupKAsVA4ou30WbxLvSQo0.png' export const WWW_URL = env.PUBLIC_WWW_URL export const listOfPagesWithoutBackButton = [ '/', diff --git a/src/lib/server/cart.ts b/src/lib/server/cart.ts index c8e538da..62039a12 100644 --- a/src/lib/server/cart.ts +++ b/src/lib/server/cart.ts @@ -1,14 +1,23 @@ -import { getBySid } from '$lib/utils/server' +import { fetchRefreshCart } from '$lib/services' +import generateUUID from '$lib/utils/generateUUID' import type { RequestEvent } from '@sveltejs/kit' export const fetchCart = async (event: RequestEvent) => { try { const cartId: string | undefined = event.cookies.get('cartId') const cartQty: string | undefined = event.cookies.get('cartQty') + + if (!cartId) { + const uuid = generateUUID() + event.cookies.set('cartId', uuid, { path: '/' }) + } if (cartId) event.locals.cartId = cartId if (cartQty) event.locals.cartQty = +cartQty - const sid = event.cookies.get('connect.sid') - const cartRes = await getBySid('carts/my', sid) + + const cartRes = await fetchRefreshCart({ + cartId + }) + const cart = { cartId: cartRes.cart_id, items: cartRes.items, @@ -16,12 +25,12 @@ export const fetchCart = async (event: RequestEvent) => { tax: cartRes.tax, subtotal: cartRes.subtotal, total: cartRes.total, - currencySymbol: cartRes.currencySymbol, - discount: cartRes.discount, - selfTakeout: cartRes.selfTakeout, - shipping: cartRes.shipping, - unavailableItems: cartRes.unavailableItems, - formattedAmount: cartRes.formattedAmount + currencySymbol: 'Rp.' + // discount: cartRes.discount, + // selfTakeout: cartRes.selfTakeout, + // shipping: cartRes.shipping, + // unavailableItems: cartRes.unavailableItems, + // formattedAmount: cartRes.formattedAmount } return cart } catch (e) { diff --git a/src/lib/services/CartService.ts b/src/lib/services/CartService.ts index a31a3315..697eb79c 100644 --- a/src/lib/services/CartService.ts +++ b/src/lib/services/CartService.ts @@ -1,18 +1,21 @@ import { provider } from '$lib/config' -import type { Error } from '$lib/types' +import type { Error, MayarAddToCart, MayarCart, Product } from '$lib/types' import { del, getAPI, post } from '$lib/utils/api' import { getBigCommerceApi, getBySid, + getMayarApi, getMedusajsApi, getWooCommerceApi, postBySid, + postMayarApi, postt } from '$lib/utils/server' import { serializeNonPOJOs } from '$lib/utils/validations' import { error } from '@sveltejs/kit' export const fetchCartData = async ({ origin, storeId, server = false, sid = null }: any) => { + console.log('fetchCartData') try { let res: any = {} switch (provider) { @@ -40,27 +43,24 @@ export const fetchCartData = async ({ origin, storeId, server = false, sid = nul } } -export const fetchRefreshCart = async ({ origin, storeId, server = false, sid = null }: any) => { +export const fetchRefreshCart = async ({ cartId }: any) => { + console.log('fetchRefreshCart') + console.log(cartId) + try { - let res: any = {} - switch (provider) { - case 'litekart': - if (server) { - res = await getBySid(`carts/refresh-cart?store=${storeId}`, sid) - // res = await getBySid(`carts/my?store=${storeId}`, sid) - } else { - res = await getAPI(`carts/refresh-cart?store=${storeId}`, origin) - } - break - case 'medusajs': - res = await getMedusajsApi(`customers/me`, {}, sid) - break - case 'bigcommerce': - res = await getBigCommerceApi(`carts/refresh-cart`, {}, sid) - break - case 'woocommerce': - res = await getWooCommerceApi(`carts/refresh-cart`, {}, sid) - break + const getCart: MayarCart = await getMayarApi(`hl/v1/cart?sessionId=${cartId}`) + if (!cartId) { + console.log('cartId undefined') + } + + const res = { + cart_id: cartId, + items: getCart.data.productItems, + qty: getCart.data.items, + tax: 0, + subtotal: 0, + total: getCart.data.amountTotal, + currencySymbol: 'Rp.' } return res || {} } catch (err) { @@ -70,6 +70,7 @@ export const fetchRefreshCart = async ({ origin, storeId, server = false, sid = } export const fetchMyCart = async ({ origin, storeId, server = false, sid = null }: any) => { + console.log('fetchMyCart') try { let res: any = {} switch (provider) { @@ -98,58 +99,33 @@ export const fetchMyCart = async ({ origin, storeId, server = false, sid = null } } -export const addToCartService = async ({ - pid, - vid, - qty, - customizedImg, - origin, - storeId, - server = false, - sid = null -}: any) => { +export const addToCartService = async ({ pid, cartId }: any) => { try { let res: any = {} - switch (provider) { - case 'litekart': - if (server) { - res = await postt( - `carts/add-to-cart`, - { - pid, - vid, - qty, - customizedImg, - store: storeId - }, - sid - ) - } else { - res = await post( - `carts/add-to-cart`, - { - pid, - vid, - qty, - customizedImg, - store: storeId - }, - origin - ) - } - break - case 'medusajs': - res = await getMedusajsApi(`customers/me`, {}, sid) - break - case 'bigcommerce': - res = await getBigCommerceApi(`carts/add-to-cart`, {}) - break - case 'woocommerce': - res = await getWooCommerceApi(`carts/add-to-cart`, {}) - break + console.log(cartId) + + if (!cartId) { + console.log('cartId undefined') } - return res || {} + + const getCart: MayarAddToCart = await postMayarApi(`hl/v1/cart/add`, { + id: pid, + sessionId: cartId + }) + + res = { + cart_id: cartId, + items: getCart.data.productItems, + qty: getCart.data.items, + tax: 0, + subtotal: 0, + total: getCart.data.amountTotal, + currencySymbol: 'Rp.' + } + + return res } catch (e) { + console.error(e.messages) throw error(e.status, e.data?.message || e.message) } } diff --git a/src/lib/services/CategoryService.ts b/src/lib/services/CategoryService.ts index a785e68d..0a2de430 100644 --- a/src/lib/services/CategoryService.ts +++ b/src/lib/services/CategoryService.ts @@ -1,8 +1,14 @@ import { provider } from '$lib/config' -import type { Error } from '$lib/types' +import type { Error, MayarAPI } from '$lib/types' import { mapMedusajsCategory } from '$lib/utils' import { getAPI } from '$lib/utils/api' -import { getBigCommerceApi, getBySid, getMedusajsApi, getWooCommerceApi } from '$lib/utils/server' +import { + getBigCommerceApi, + getBySid, + getMedusajsApi, + getWooCommerceApi, + getMayarApi +} from '$lib/utils/server' import { serializeNonPOJOs } from '$lib/utils/validations' import { error } from '@sveltejs/kit' @@ -65,6 +71,14 @@ export const fetchCategory = async ({ origin, slug, id, server = false, sid = nu case 'woocommerce': res = await getWooCommerceApi(`categories`, {}, sid) break + case 'mayar': + const mayarResultAPI: MayarAPI = await getMayarApi('hl/v1/product') + mayarResultAPI.data.map((result, index) => { + let currentCat = '' + if (currentCat !== result.category) { + res + } + }) } return res || {} } catch (e) { diff --git a/src/lib/services/HomeService.ts b/src/lib/services/HomeService.ts index a715f331..e9ac82b8 100644 --- a/src/lib/services/HomeService.ts +++ b/src/lib/services/HomeService.ts @@ -1,32 +1,11 @@ import { error } from '@sveltejs/kit' -import { getAPI } from '$lib/utils/api' -import { getBigCommerceApi, getBySid, getMedusajsApi, getWooCommerceApi } from '$lib/utils/server' -import { provider } from '$lib/config' -import { serializeNonPOJOs } from '$lib/utils/validations' -import type { Error } from '$lib/types' +import { getMayarApi } from '$lib/utils/server' +import type { MayarAPI } from '$lib/types' -export const fetchHome = async ({ origin, storeId, server = false, sid = null }: any) => { +export const fetchHome = async () => { try { - let res: any = {} - switch (provider) { - case 'litekart': - if (server) { - res = await getBySid(`home?store=${storeId}`, sid) - } else { - res = await getAPI(`home?store=${storeId}`, origin) - } - break - case 'medusajs': - res = await getMedusajsApi(`products`, {}, sid) - break - case 'bigcommerce': - res = await getBigCommerceApi(`home`, {}, sid) - break - case 'woocommerce': - res = await getWooCommerceApi(`home`, {}, sid) - break - } - return res || {} + const res: MayarAPI = await getMayarApi('hl/v1/product') + return res.data || [] } catch (e) { throw error(e.status, e.data?.message || e.message) } diff --git a/src/lib/services/ProductService.ts b/src/lib/services/ProductService.ts index d2f7a569..6b2cd7ac 100644 --- a/src/lib/services/ProductService.ts +++ b/src/lib/services/ProductService.ts @@ -5,7 +5,8 @@ import { getBySid, getMedusajsApi, getWooCommerceApi, - postMedusajsApi + postMedusajsApi, + getMayarApi } from '$lib/utils/server' import { mapBigcommerceProducts, @@ -15,7 +16,14 @@ import { } from '$lib/utils' import { provider } from '$lib/config' import { serializeNonPOJOs } from '$lib/utils/validations' -import type { AllProducts, Error, Product } from '$lib/types' +import type { + AllProducts, + Error, + MayarAPI, + MayarDetailProduct, + MayarSearch, + Product +} from '$lib/types' // Search product @@ -28,45 +36,72 @@ export const searchProducts = async ({ sid = null }: any) => { try { - let res: AllProducts | {} = {} + let allProduct: AllProducts | {} = {} let products: Product[] = [] let count = 0 let facets = '' let pageSize = 0 let category = '' let err = '' - switch (provider) { - case 'litekart': - if (server) { - res = await getBySid(`es/products?${query}&store=${storeId}`, sid) - } else { - res = await getAPI(`es/products?${query}&store=${storeId}`, origin) + + const res: MayarSearch = await getMayarApi(`hl/v1/product/07e9d941-1538-41f7-b01d-ad251e4d3b63`) + if (res.data.length > 0) { + res.data.map((productItem) => { + let product: Product = { + id: productItem.id, + _id: productItem.id, + active: true, + barcode: '', + countryOfOrigin: '', + description: productItem.description, + discount: 0, + ean: '', + hasStock: productItem.qty > 0 ? true : false, + height: 96, + hsn: '', + images: [], + img: '', + isCustomized: false, + mrp: 0, + name: productItem.name, + new: true, + price: productItem.amount, + sku: '', + slug: productItem.link, + status: '', + stock: productItem.qty, + weight: 200, + width: 75, + categoryPool: undefined, + tags: [] } - res = res || {} - products = res.data.map((p) => { - const p1 = { ...p._source } - p1.id = p._id - return p1 - }) - count = res?.count - facets = res?.facets - pageSize = res?.pageSize - err = !res?.estimatedTotalHits ? 'No result Not Found' : null - break - case 'medusajs': - res = await postMedusajsApi(`products/search?q=${searchData}`, {}, sid) - products = res?.products - count = res?.count - facets = res?.facets || [] - pageSize = res?.pageSize || 25 - break - case 'bigcommerce': - res = await getBigCommerceApi(`products?${query}`, {}, sid) - break - case 'woocommerce': - res = await getWooCommerceApi(`products?${query}`, {}, sid) - break + + if (productItem.multipleImage.length > 0) { + productItem.multipleImage.map((img) => { + product.images.push(img.url) + }) + } + + if (productItem.coverImage) { + product.img = productItem.coverImage.url + } + + products.push(product) + }) + } + + allProduct = { + count: res.data.length, + currentPage: res.page, + pageSize: res.pageSize, + limit: res.pageCount, + products: products, + facets: [] } + + count = res.pageCount + pageSize = res.pageSize + console.log({ products, count, facets, pageSize, err }) return { products, count, facets, pageSize, err } } catch (e) { throw error(e.status, e.data?.message || e.message) @@ -77,26 +112,7 @@ export const searchProducts = async ({ export const fetchProducts = async ({ origin, slug, id, server = false, sid = null }: any) => { try { - let res: AllProducts | {} = {} - switch (provider) { - case 'litekart': - if (server) { - res = await getBySid(`products?store=${storeId}`, sid) - } else { - res = await getAPI(`products?store=${storeId}`, origin) - } - break - case 'medusajs': - const med = (await getMedusajsApi(`products`, {}, sid)).product - res = mapMedusajsAllProducts(med) - break - case 'bigcommerce': - res = await getBigCommerceApi(`products`, {}, sid) - break - case 'woocommerce': - res = await getWooCommerceApi(`products`, {}, sid) - break - } + const res: MayarAPI = await getMayarApi('hl/v1/product') return res?.data || [] } catch (e) { @@ -106,33 +122,68 @@ export const fetchProducts = async ({ origin, slug, id, server = false, sid = nu // Fetch single product -export const fetchProduct = async ({ origin, slug, id, server = false, sid = null }: any) => { +export const fetchProduct = async ({ slug }: { slug: string }) => { try { - let res: Product | {} = {} - switch (provider) { - case 'litekart': - if (server) { - res = await getBySid(`products/${slug}`, sid) - } else { - res = await getAPI(`products/${slug}`, origin) - } - break - case 'medusajs': - const med = (await getMedusajsApi(`products/${id}`, {}, sid)).product - res = mapMedusajsProduct(med) - break - case 'bigcommerce': - const bi = (await getBigCommerceApi(`products/${id}`, {}, sid)).data - const images = (await getBigCommerceApi(`products/${id}/images`, {}, sid)).data - bi.images = images - res = mapBigcommerceProducts(bi) - break - case 'woocommerce': - const wo = (await getWooCommerceApi(`products/${id}`, {}, sid)).data - res = mapWoocommerceProducts(wo) - break + const res: MayarDetailProduct = await getMayarApi(`hl/v1/product/${slug}`) + let product: Product | {} = {} + + if (res.data.type === 'physical_product') { + product = { + id: res.data.id, + _id: res.data.id, + active: true, + barcode: '', + countryOfOrigin: '', + description: res.data.description, + discount: 0, + ean: '', + hasStock: res.data.qty > 0 ? true : false, + height: 96, + hsn: '', + images: res.data.multipleImage, + img: res.data.coverImage, + isCustomized: false, + mrp: 0, + name: res.data.name, + new: true, + price: res.data.amount, + sku: '', + slug: res.data.link, + status: '', + stock: res.data.qty, + weight: 200, + width: 75 + } + } else { + product = { + id: res.data.id, + _id: res.data.id, + active: true, + barcode: '', + countryOfOrigin: '', + description: res.data.description, + discount: 0, + ean: '', + hasStock: res.data.limit > 0 ? true : false, + height: 96, + hsn: '', + images: [res.data.coverImage], + img: res.data.coverImage, + isCustomized: false, + mrp: 0, + name: res.data.name, + new: true, + price: res.data.amount, + sku: '', + slug: res.data.link, + status: '', + stock: res.data.qty, + weight: 200, + width: 75 + } } - return res || {} + + return product || {} } catch (e) { throw error(e.status, e.data?.message || e.message) } diff --git a/src/lib/types.d.ts b/src/lib/types.d.ts index 9d37b765..577e7585 100644 --- a/src/lib/types.d.ts +++ b/src/lib/types.d.ts @@ -35,12 +35,24 @@ interface AllProducts { facets: Facet[] } +interface MayarSearch { + statusCode: number + messages: string + hasMore: boolean + pageCount: number + pageSize: number + page: number + data: MayarProduct[] + total: number +} + interface Facet {} interface EsProduct { _source: Product } interface Product { + product: any id?: string _id: string active?: boolean @@ -153,6 +165,60 @@ interface AllOrders { data: Order[] } +interface MayarCart { + statusCode: number + messages: string + data: { + typeCart: string + userId: string + sessionId: string + items: number + amountTotal: number + productItems: { + qty: number + amount: number + product: { + id: string + link: string + name: string + category: null | string + type: string + qty: null | number + amount: number + limit: number + status: string + userId: string + description: string + coverImageId: string + multipleImageId: null | string + multipleImage: IMultipleImage[] + user: { + id: string + accountId: string + } + coverImage: { + id: string + fileType: string + url: string + } + } + }[] + } +} + +interface MayarAddToCart { + statusCode: number + messages: string + data: { + typeCart: string + userId: string + sessionId: string + items: number + amountTotal: number + productItems: MayarProduct[] + } +} + interface CartItem { pid: ID vid: ID @@ -619,3 +685,56 @@ interface Wishlist { user: string variant: string } + +interface MayarAPI { + statusCode: number + messages: string + hasMore: boolean + pageCount: number + pageSize: number + page: number + data: MayarProduct[] + total: number +} + +interface MayarProduct { + id: string + amount: null | number + category: string + createdAt: number + description: string + link: string + type: string + status: string + name: string + limit: null | number + redirectUrl: string + event: any + order: any + path: string + coverImageId: null | string + multipleImageId: null | string + multipleImage: null | IMultipleImage[] + coverImage: null | ICover + qty?: number +} + +interface MayarDetailProduct { + statusCode: number + messages: string + data: MayarProduct +} + +interface ICover { + id: string + fileType: string + url: string +} + +interface IMultipleImage { + id: string + fileType: string + createdAt: Date + updatedAt: Date + url: string +} diff --git a/src/lib/utils/generateUUID.ts b/src/lib/utils/generateUUID.ts new file mode 100644 index 00000000..da5650fa --- /dev/null +++ b/src/lib/utils/generateUUID.ts @@ -0,0 +1,12 @@ +function generateUUID() { + let d = new Date().getTime() + const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + const r = (d + Math.random() * 16) % 16 | 0 + d = Math.floor(d / 16) + return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16) + }) + + return uuid +} + +export default generateUUID diff --git a/src/lib/utils/index.ts b/src/lib/utils/index.ts index 0e84d9c9..69681522 100644 --- a/src/lib/utils/index.ts +++ b/src/lib/utils/index.ts @@ -96,7 +96,7 @@ export function truncate(text: string, stop: number, clamp: string) { else return '' } -export function currency(value: any, currency = '$', decimals?: number) { +export function currency(value: any, currency = 'Rp.', decimals?: number) { const digitsRE = /(\d{3})(?=\d)/g value = parseFloat(value) if (!isFinite(value) || (!value && value !== 0)) return '' diff --git a/src/lib/utils/server.ts b/src/lib/utils/server.ts index 55cd24a2..fda0a798 100644 --- a/src/lib/utils/server.ts +++ b/src/lib/utils/server.ts @@ -45,6 +45,7 @@ export async function postt(endpoint: string, data: any, ck?: any) { if (res?.status > 399) { throw { status: res.status, message: res } } else if (response?.status > 399) { + console.log('Error 1') throw { status: response.status, message: res } } else { return res @@ -60,6 +61,8 @@ export const delBySid = async (endpoint: string, sid?: any) => { const isJson = response.headers.get('content-type')?.includes('application/json') const res = isJson ? await response.json() : await response.text() if (response?.status > 399) { + console.log('Error 2') + throw { status: response.status, message: response.statusText } } else { return res @@ -83,6 +86,7 @@ export async function postBySid(endpoint: string, data: any, sid?: string) { if (res?.status > 399) { throw { status: res.status, message: res } } else if (response?.status > 399) { + console.log('Error 3') throw { status: response.status, message: res } } else { return res @@ -116,6 +120,7 @@ export const getBySid = async (endpoint: string, sid?: any) => { const isJson = response.headers.get('content-type')?.includes('application/json') const res = isJson ? await response.json() : await response.text() if (response?.status > 399) { + console.log('Error 5') throw { status: response.status, message: response.statusText } } else { return res @@ -240,3 +245,45 @@ export const postWooCommerceApi = async (endpoint: string, query: any, sid?: any // console.log('eeeeeeeeeeeeee', e.message) } } + +export const getMayarApi = async (endpoint: string) => { + const response = await fetch('https://api.mayar.club' + '/' + endpoint, { + method: 'GET', + headers: { + Authorization: + 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNGUyOWU2Ni00NmNhLTQzZDctOWM4YS1mYWMwMTY2NzViZmYiLCJhY2NvdW50SWQiOiJiNDE3MWIyNy1jYWVkLTRiZGUtYjNkMi05ODZiYWNlMzkyMjciLCJjcmVhdGVkQXQiOiIxNjc2NTIyMTc4OTI2Iiwicm9sZSI6ImRldmVsb3BlciIsInN1YiI6ImRlbHZpZXJvbmlnZWxAZ21haWwuY29tIiwibmFtZSI6Im5pZ2VsZGVsdmllcm8iLCJsaW5rIjoibmlnZWwiLCJpc1NlbGZEb21haW4iOm51bGwsImlhdCI6MTY3NjUyMjE3OH0.dXZFa5kcMLjhPu7GaaLUsRoh5hLRF4QA78UT-iT2VbREev3mvEIsUqc-xKc6C9FQaiLHDAvwC-oD05wzFhmv3lQV1UVtXGoJG0GC4Eumb-UX3QR6-glHyQaIPj2USlPug6wrBo1CKoM5l7LiPiqVPcr3vro0zZJzrK-gFZ15CBDYcVdEWw-9VLnpNj21RUbbPEnLdv8o283XHJ0_KmHINH0JY2x2hHW-Mb77ZZcU3qwBkYpG8ZXDQeMsf4zeoOhbVAtGtFOK9EzjXrEU2hHNbaAdlA50019IAgC8P0NRj8odTi3CPnl6UOUTVQvh9D3UwO3yLUKQ0l_vnjDfZKao8w' + } + }) + + // const isJson = response.headers.get('content-type')?.includes('application/json') + const res = await response.json() + if (res?.status > 399) { + throw { status: res.status, message: res } + } else if (response?.status > 399) { + throw { status: response.status, message: res } + } else { + return res + } +} + +export const postMayarApi = async (endpoint: string, body: any) => { + const response = await fetch('https://api.mayar.club' + '/' + endpoint, { + method: 'POST', + headers: { + Authorization: + 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxNGUyOWU2Ni00NmNhLTQzZDctOWM4YS1mYWMwMTY2NzViZmYiLCJhY2NvdW50SWQiOiJiNDE3MWIyNy1jYWVkLTRiZGUtYjNkMi05ODZiYWNlMzkyMjciLCJjcmVhdGVkQXQiOiIxNjc2NTIyMTc4OTI2Iiwicm9sZSI6ImRldmVsb3BlciIsInN1YiI6ImRlbHZpZXJvbmlnZWxAZ21haWwuY29tIiwibmFtZSI6Im5pZ2VsZGVsdmllcm8iLCJsaW5rIjoibmlnZWwiLCJpc1NlbGZEb21haW4iOm51bGwsImlhdCI6MTY3NjUyMjE3OH0.dXZFa5kcMLjhPu7GaaLUsRoh5hLRF4QA78UT-iT2VbREev3mvEIsUqc-xKc6C9FQaiLHDAvwC-oD05wzFhmv3lQV1UVtXGoJG0GC4Eumb-UX3QR6-glHyQaIPj2USlPug6wrBo1CKoM5l7LiPiqVPcr3vro0zZJzrK-gFZ15CBDYcVdEWw-9VLnpNj21RUbbPEnLdv8o283XHJ0_KmHINH0JY2x2hHW-Mb77ZZcU3qwBkYpG8ZXDQeMsf4zeoOhbVAtGtFOK9EzjXrEU2hHNbaAdlA50019IAgC8P0NRj8odTi3CPnl6UOUTVQvh9D3UwO3yLUKQ0l_vnjDfZKao8w', + 'Content-Type': 'application/json' + }, + body: JSON.stringify(body) + }) + + // const isJson = response.headers.get('content-type')?.includes('application/json') + const res = await response.json() + if (res?.status > 399) { + throw { status: res.status, message: res } + } else if (response?.status > 399) { + throw { status: response.status, message: res } + } else { + return res + } +} diff --git a/src/routes/(app)/+page.server.ts b/src/routes/(app)/+page.server.ts index 5eaffad8..afa4708e 100644 --- a/src/routes/(app)/+page.server.ts +++ b/src/routes/(app)/+page.server.ts @@ -4,31 +4,19 @@ import { fetchDeals } from '$lib/services/DealsService' import { fetchHome } from '$lib/services/HomeService' import { error } from '@sveltejs/kit' -export async function load({ locals, setHeaders }) { - const { store, origin } = locals - // console.log('Store ID.............', locals.store?.id) +export async function load() { try { - let home - // const cached = await redis.get(`home-www-${locals.store?.id}`) - // if (cached) { - // console.log('Cache hit!') - // home = JSON.parse(cached) - // } else { - // console.log('Cache miss!') - home = await fetchHome({ storeId: store?.id, server: true }) - // setHeaders({ 'cache-control': 'max-age: 600' }) - // redis.set(`home-www-${locals.store?.id}`, JSON.stringify(home), 'EX', 600) - // } + const home = await fetchHome() const deals = [] //await fetchDeals({ storeId: store?.id, server: true }) if (home) { return { home: home, deals: deals || {} } } } catch (e) { + console.log('Error Home') + throw error( 404, - `Store Not Found @Page -
ID: ${store.id} -
ORIGIN: ${origin} + `Store Not Found @Page
DOMAIN(env):${DOMAIN}
HTTP_ENDPOINT(env):${HTTP_ENDPOINT}` ) diff --git a/src/routes/(app)/+page.svelte b/src/routes/(app)/+page.svelte index 60ec8e74..c39ace34 100644 --- a/src/routes/(app)/+page.svelte +++ b/src/routes/(app)/+page.svelte @@ -26,7 +26,7 @@ let seoProps = { // addressRegion: 'Odisha', // alternateJsonHref: '', // alternateXml: { title: '', href: '' }, - brand: $page.data.store?.title, + brand: 'Mayar Commerce', // breadcrumbs: '', caption: $page.data.store?.title, category: $page.data.store?.title, @@ -39,8 +39,8 @@ let seoProps = { // gtin: '', // height: '', id: $page?.url?.href, - image: $page.data.store?.logo, - logo: $page.data.store?.logo, + image: 'https://framerusercontent.com/images/0aaSOxupKAsVA4ou30WbxLvSQo0.png', + logo: 'https://framerusercontent.com/images/0aaSOxupKAsVA4ou30WbxLvSQo0.png', ogSquareImage: { url: '', width: 56, height: 56 }, openingHours: ['Monday,Tuesday,Wednesday,Thursday,Friday,Saturday 08:00-13:00'], // popularity: product.popularity, @@ -92,10 +92,21 @@ $: heroBanners = data.home?.banners?.data.filter((b) => { return b.type === 'hero' }) + +export let currentPage = 1 +export let totalPages = 10 + +const handlePageClick = (page) => { + currentPage = page +} + + Mayar Commerce + +
@@ -122,14 +133,79 @@ $: heroBanners = - {#if data.home?.categories?.data?.length > 0} + {#if data.home.length > 0}