Skip to content

Commit

Permalink
Implemented with mayar.id
Browse files Browse the repository at this point in the history
  • Loading branch information
nigeldelviero committed Mar 23, 2023
1 parent 9e65eea commit f2b2320
Show file tree
Hide file tree
Showing 26 changed files with 687 additions and 470 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,8 @@
"zod": "3.20.6",
"zod-form-data": "1.3.1"
},
"type": "module"
"type": "module",
"dependencies": {
"svelte-paginate": "0.1.0"
}
}
7 changes: 4 additions & 3 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,18 @@ 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
// event.cookies.set('sid', derivedSid, { path: '/' })
// event.request.headers.delete('connection')
return await resolve(event)
} catch (e) {
const err = `Store Not Found @Hook
const err = `Store Not Found @Hook
<br/>ID: ${event.locals.store?.id}
<br/>ORIGIN: ${event.locals?.origin}
<br/>DOMAIN(env): ${DOMAIN}
Expand Down
12 changes: 6 additions & 6 deletions src/lib/Nav.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ async function onSearchSubmit({ detail }) {
{/if}

{#if me?.active}
<div
<!-- <div
class="relative hidden lg:block"
on:mouseenter="{() => (showDropdownAccount = true)}"
on:mouseleave="{() => (showDropdownAccount = false)}">
Expand Down Expand Up @@ -464,11 +464,11 @@ async function onSearchSubmit({ detail }) {
</li>
</ul>
{/if}
</div>
</div> -->

<!-- Menu -->

<button
<!-- <button
aria-label="Sidebar"
type="button"
class="focus:outline-none lg:hidden"
Expand All @@ -485,11 +485,11 @@ async function onSearchSubmit({ detail }) {
stroke-linejoin="round"
d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"></path>
</svg>
</button>
</button> -->
{:else}
<!-- Login -->

<a
<!-- <a
href="{$page.data?.loginUrl || '/auth/login'}?ref={$page?.url?.pathname}{$page?.url
?.search}"
aria-label="Click to route login"
Expand All @@ -515,7 +515,7 @@ async function onSearchSubmit({ detail }) {
Login
</span>
</button>
</a>
</a> -->
{/if}
</div>
</div>
Expand Down
19 changes: 14 additions & 5 deletions src/lib/components/Pricesummary.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ function submit() {
<div class="mt-2 flex items-center justify-between font-medium">
<h4>Total</h4>

<h4>{cart.formattedAmount?.subtotal || '-'}</h4>
<h4>
{cart.total.toLocaleString('id-ID', {
style: 'currency',
currency: 'IDR'
}) || '-'}
</h4>
</div>

{#if cart?.savings > 0}
Expand Down Expand Up @@ -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}`)}">
<span>{text}</span>

{#if showNextIcon}
Expand All @@ -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}`)}">
<span>{text}</span>

{#if showNextIcon}
Expand Down Expand Up @@ -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}`)}">
<span>{text}</span>

{#if showNextIcon}
Expand All @@ -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}`)}">
<span>{text}</span>

{#if showNextIcon}
Expand Down
5 changes: 3 additions & 2 deletions src/lib/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)',
Expand Down Expand Up @@ -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 = [
'/',
Expand Down
27 changes: 18 additions & 9 deletions src/lib/server/cart.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
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,
qty: cartRes.qty,
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) {
Expand Down
114 changes: 45 additions & 69 deletions src/lib/services/CartService.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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)
}
}
Expand Down
18 changes: 16 additions & 2 deletions src/lib/services/CategoryService.ts
Original file line number Diff line number Diff line change
@@ -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'

Expand Down Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit f2b2320

Please sign in to comment.