feat: disable Wishlist

chore: setup commerce & next config
fix: replace all call to bigcommerce from aquilacms provider
feat add validation to input in signup
This commit is contained in:
Gérard Le Cloerec 2021-04-06 15:08:19 +02:00
parent 94861a922a
commit a5de31ae17
68 changed files with 2157 additions and 7640 deletions

View File

@ -1,6 +1,7 @@
{
"provider": "aquilacms",
"features": {
"wishlist": true,
"wishlist": false,
"customCheckout": false
}
}

View File

@ -48,11 +48,13 @@ const SignUpView: FC<Props> = () => {
const handleValidation = useCallback(() => {
// Test for Alphanumeric password
const validPassword = /^(?=.*[a-zA-Z])(?=.*[0-9])/.test(password)
const validPassword = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d:])([^\s]){6,}$/.test(
password
)
// Unable to send form unless fields are valid.
if (dirty) {
setDisabled(!validate(email) || password.length < 7 || !validPassword)
setDisabled(!validate(email) || password.length < 6 || !validPassword)
}
}, [email, password, dirty])
@ -81,8 +83,8 @@ const SignUpView: FC<Props> = () => {
<Info width="15" height="15" />
</span>{' '}
<span className="leading-6 text-sm">
<strong>Info</strong>: Passwords must be longer than 7 chars and
include numbers.{' '}
<strong>Info</strong>: Passwords must be longer than 6 chars and
include numbers, upper and lower case.{' '}
</span>
</span>
<div className="pt-2 w-full flex flex-col">

View File

@ -120,7 +120,7 @@ const CartSidebarView: FC = () => {
</li>
<li className="flex justify-between py-1">
<span>Estimated Shipping</span>
<span className="font-bold tracking-wide">FREE</span>
<span>Calculated at checkout</span>
</li>
</ul>
<div className="flex justify-between border-t border-accents-3 py-3 font-bold mb-10">

View File

@ -15,7 +15,7 @@ interface Props {
pages?: Page[]
}
const LEGAL_PAGES = ['terms-of-use', 'shipping-returns', 'privacy-policy']
const LEGAL_PAGES = ['legal-notice', 'terms']
const Footer: FC<Props> = ({ className, pages }) => {
const { sitePages, legalPages } = usePages(pages)
@ -37,7 +37,7 @@ const Footer: FC<Props> = ({ className, pages }) => {
</div>
<div className="col-span-1 lg:col-span-2">
<ul className="flex flex-initial flex-col md:flex-1">
<li className="py-3 md:py-0 md:pb-4">
{/* <li className="py-3 md:py-0 md:pb-4">
<Link href="/">
<a className="text-primary hover:text-accents-6 transition ease-in-out duration-150">
Home
@ -57,7 +57,7 @@ const Footer: FC<Props> = ({ className, pages }) => {
Blog
</a>
</Link>
</li>
</li> */}
{sitePages.map((page) => (
<li key={page.url} className="py-3 md:py-0 md:pb-4">
<Link href={page.url!}>

View File

@ -2,10 +2,10 @@ import React, { FC, useState } from 'react'
import cn from 'classnames'
import { useUI } from '@components/ui'
import { Heart } from '@components/icons'
import useAddItem from '@framework/wishlist/use-add-item'
// import useAddItem from '@framework/wishlist/use-add-item'
import useCustomer from '@framework/customer/use-customer'
import useWishlist from '@framework/wishlist/use-wishlist'
import useRemoveItem from '@framework/wishlist/use-remove-item'
// import useWishlist from '@framework/wishlist/use-wishlist'
// import useRemoveItem from '@framework/wishlist/use-remove-item'
import type { Product, ProductVariant } from '@commerce/types'
type Props = {
@ -19,8 +19,11 @@ const WishlistButton: FC<Props> = ({
className,
...props
}) => {
// @ts-ignore
const { data } = useWishlist()
// @ts-ignore
const addItem = useAddItem()
// @ts-ignore
const removeItem = useRemoveItem()
const { data: customer } = useCustomer()
const { openModal, setModalView } = useUI()

View File

@ -10,7 +10,7 @@ import { useUI } from '@components/ui/context'
import type { Product } from '@commerce/types'
import usePrice from '@framework/product/use-price'
import useAddItem from '@framework/cart/use-add-item'
import useRemoveItem from '@framework/wishlist/use-remove-item'
// import useRemoveItem from '@framework/wishlist/use-remove-item'
interface Props {
product: Product

View File

@ -1,6 +1,2 @@
BIGCOMMERCE_STOREFRONT_API_URL=
BIGCOMMERCE_STOREFRONT_API_TOKEN=
BIGCOMMERCE_STORE_API_URL=
BIGCOMMERCE_STORE_API_TOKEN=
BIGCOMMERCE_STORE_API_CLIENT_ID=
BIGCOMMERCE_CHANNEL_ID=
AQUILACMS_URL=
AQUILACMS_API_URL=

View File

@ -1,6 +1,7 @@
import { parseCartItem } from '../../utils/parse-item'
import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const addItem: CartHandlers['addItem'] = async ({
res,
@ -14,32 +15,23 @@ const addItem: CartHandlers['addItem'] = async ({
})
}
if (!item.quantity) item.quantity = 1
const options = {
method: 'POST',
const result: AquilacmsCart = await config.storeApiFetch('/v2/cart/item', {
method: 'PUT',
body: JSON.stringify({
line_items: [parseCartItem(item)],
...(!cartId && config.storeChannelId
? { channel_id: config.storeChannelId }
: {}),
cartId,
item: {
id: item.productId,
quantity: item.quantity,
},
}),
}
const { data } = cartId
? await config.storeApiFetch(
`/v3/carts/${cartId}/items?include=line_items.physical_items.options`,
options
)
: await config.storeApiFetch(
'/v3/carts?include=line_items.physical_items.options',
options
)
})
// Create or update the cart cookie
res.setHeader(
'Set-Cookie',
getCartCookie(config.cartCookie, data.id, config.cartCookieMaxAge)
getCartCookie(config.cartCookie, result._id, config.cartCookieMaxAge)
)
res.status(200).json({ data })
res.status(200).json({ data: normalizeCart(result) })
}
export default addItem

View File

@ -2,6 +2,7 @@ import type { AquilacmsCart } from '../../../types'
import { AquilacmsApiError } from '../../utils/errors'
import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..'
import { normalizeCart } from '../../../lib/normalize'
// Return current cart info
const getCart: CartHandlers['getCart'] = async ({
@ -9,13 +10,21 @@ const getCart: CartHandlers['getCart'] = async ({
body: { cartId },
config,
}) => {
let result: { data?: AquilacmsCart } = {}
if (cartId) {
try {
result = await config.storeApiFetch(
`/v3/carts/${cartId}?include=line_items.physical_items.options`
let result: AquilacmsCart = await config.storeApiFetch(
`/v2/cart/${cartId}`,
{
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
populate: ['items.id'],
},
}),
}
)
return res.status(200).json({ data: normalizeCart(result) })
} catch (error) {
if (error instanceof AquilacmsApiError && error.status === 404) {
// Remove the cookie if it exists but the cart wasn't found
@ -25,8 +34,7 @@ const getCart: CartHandlers['getCart'] = async ({
}
}
}
res.status(200).json({ data: result.data ?? null })
res.status(200).json({ data: null })
}
export default getCart

View File

@ -1,5 +1,7 @@
import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const removeItem: CartHandlers['removeItem'] = async ({
res,
@ -13,11 +15,13 @@ const removeItem: CartHandlers['removeItem'] = async ({
})
}
const result = await config.storeApiFetch<{ data: any } | null>(
`/v3/carts/${cartId}/items/${itemId}?include=line_items.physical_items.options`,
{ method: 'DELETE' }
const result: AquilacmsCart = await config.storeApiFetch(
`/v2/cart/${cartId}/item/${itemId}`,
{
method: 'DELETE',
}
)
const data = result?.data ?? null
let data = normalizeCart(result) ?? null
res.setHeader(
'Set-Cookie',

View File

@ -1,6 +1,7 @@
import { parseCartItem } from '../../utils/parse-item'
import getCartCookie from '../../utils/get-cart-cookie'
import type { CartHandlers } from '..'
import { AquilacmsCart } from '../../../types'
import { normalizeCart } from '../../../lib/normalize'
const updateItem: CartHandlers['updateItem'] = async ({
res,
@ -14,14 +15,19 @@ const updateItem: CartHandlers['updateItem'] = async ({
})
}
const { data } = await config.storeApiFetch(
`/v3/carts/${cartId}/items/${itemId}?include=line_items.physical_items.options`,
{
const options = {
method: 'PUT',
body: JSON.stringify({
line_item: parseCartItem(item),
item: {
_id: itemId,
quantity: item.quantity,
},
cartId,
}),
}
const result: AquilacmsCart = await config.storeApiFetch(
'/v2/cart/updateqty',
options
)
// Update the cart cookie
@ -29,7 +35,7 @@ const updateItem: CartHandlers['updateItem'] = async ({
'Set-Cookie',
getCartCookie(config.cartCookie, cartId, config.cartCookieMaxAge)
)
res.status(200).json({ data })
res.status(200).json({ data: normalizeCart(result) })
}
export default updateItem

View File

@ -14,19 +14,20 @@ import type {
AddCartItemHandlerBody,
UpdateCartItemHandlerBody,
RemoveCartItemHandlerBody,
Cart,
} from '../../types'
export type CartHandlers = {
getCart: AquilacmsHandler<AquilacmsCart, GetCartHandlerBody>
addItem: AquilacmsHandler<AquilacmsCart, AddCartItemHandlerBody>
updateItem: AquilacmsHandler<AquilacmsCart, UpdateCartItemHandlerBody>
removeItem: AquilacmsHandler<AquilacmsCart, RemoveCartItemHandlerBody>
getCart: AquilacmsHandler<Cart, GetCartHandlerBody>
addItem: AquilacmsHandler<Cart, AddCartItemHandlerBody>
updateItem: AquilacmsHandler<Cart, UpdateCartItemHandlerBody>
removeItem: AquilacmsHandler<Cart, RemoveCartItemHandlerBody>
}
const METHODS = ['GET', 'POST', 'PUT', 'DELETE']
// TODO: a complete implementation should have schema validation for `req.body`
const cartApi: AquilacmsApiHandler<AquilacmsCart, CartHandlers> = async (
const cartApi: AquilacmsApiHandler<Cart, CartHandlers> = async (
req,
res,
config,

View File

@ -1,5 +1,6 @@
import { Product } from '@commerce/types'
import getAllProducts, { ProductEdge } from '../../../product/get-all-products'
import { normalizeProduct } from '../../../lib/normalize'
import getAllProducts from '../../../product/get-all-products'
import type { ProductsHandlers } from '../products'
const SORT: { [key: string]: string | undefined } = {
@ -13,65 +14,87 @@ const LIMIT = 12
// Return current cart info
const getProducts: ProductsHandlers['getProducts'] = async ({
res,
body: { search, category, brand, sort },
body: { search, category, brand, sort: sortParam },
config,
}) => {
// Use a dummy base as we only care about the relative path
const url = new URL('/v3/catalog/products', 'http://a')
let filter: any = {}
let sort = {}
url.searchParams.set('is_visible', 'true')
url.searchParams.set('limit', String(LIMIT))
if (search) filter['$text'] = { $search: search }
if (search) url.searchParams.set('keyword', search)
if (category) {
const cat: any = await config.storeApiFetch('/v2/category', {
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
filter: {
_id: category,
},
structure: {
productsList: 1,
},
page: 1,
limit: 1,
},
}),
})
if (category && Number.isInteger(Number(category)))
url.searchParams.set('categories:in', category)
const productIds: string[] = cat.productsList
.filter((p: any) => p.checked)
.map((p: any) => p.id)
// if (search) {
// filter = {
// $and: [{ ...filter }, { _id: { $in: productIds } }],
// }
// } else {
filter = {
_id: { $in: productIds },
}
// }
}
if (brand && Number.isInteger(Number(brand)))
url.searchParams.set('brand_id', brand)
if (sort) {
const [_sort, direction] = sort.split('-')
if (sortParam) {
const [_sort, direction] = sortParam.split('-')
const sortValue = SORT[_sort]
if (sortValue && direction) {
url.searchParams.set('sort', sortValue)
url.searchParams.set('direction', direction)
switch (sortValue) {
case 'latest':
// 'desc'
console.log(`sort by ${sortValue} not implemented`)
case 'trending':
// 'desc'
console.log(`sort by ${sortValue} not implemented`)
case 'price':
if (direction === 'asc') sort = { 'price.priceSort.ati': 1 }
else if (direction === 'desc') sort = { 'price.priceSort.ati': -1 }
}
}
}
// We only want the id of each product
url.searchParams.set('include_fields', 'id')
const { data } = await config.storeApiFetch<{ data: { id: number }[] }>(
url.pathname + url.search
)
const entityIds = data.map((p) => p.id)
const found = entityIds.length > 0
// We want the GraphQL version of each product
const graphqlData = await getAllProducts({
variables: { first: LIMIT, entityIds },
config,
const { datas } = await config.storeApiFetch('/v2/products', {
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
filter,
structure: {
canonical: 1,
reviews: 1,
stock: 1,
universe: 1,
},
// populate: ['bundle_sections.products.id'],
sort,
page: 1,
limit: LIMIT,
},
}),
})
// Put the products in an object that we can use to get them by id
const productsById = graphqlData.products.reduce<{
[k: number]: Product
}>((prods, p) => {
prods[Number(p.id)] = p
return prods
}, {})
const products: Product[] = found ? [] : graphqlData.products
// Populate the products array with the graphql products, in the order
// assigned by the list of entity ids
entityIds.forEach((id) => {
const product = productsById[id]
if (product) products.push(product)
})
const found = datas ? datas.length > 0 : false
const products = datas ? datas.map(normalizeProduct) : []
res.status(200).json({ data: { products, found } })
}

View File

@ -5,7 +5,7 @@ import createApiHandler, {
import { AquilacmsApiError } from './utils/errors'
const METHODS = ['GET']
const fullCheckout = true
const fullCheckout = false
// TODO: a complete implementation should have schema validation for `req.body`
const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
@ -13,6 +13,8 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
const { cookies } = req
const cartId = cookies[config.cartCookie]
const token = cookies[config.customerCookie]
console.log(config.customerCookie, cookies)
try {
if (!cartId) {
@ -20,14 +22,13 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
return
}
if (fullCheckout) {
const { data } = await config.storeApiFetch(
`/v3/carts/${cartId}/redirect_urls`,
`/v/carts/${cartId}/redirect_urls`,
{
method: 'POST',
}
)
if (fullCheckout) {
res.redirect(data.checkout_url)
return
}
@ -40,20 +41,13 @@ const checkoutApi: AquilacmsApiHandler<any> = async (req, res, config) => {
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Checkout</title>
<script src="https://checkout-sdk.bigcommerce.com/v1/loader.js"></script>
<script>
window.onload = function() {
checkoutKitLoader.load('checkout-sdk').then(function (service) {
service.embedCheckout({
containerId: 'checkout',
url: '${data.embedded_checkout_url}'
});
});
window.onload = () => {
window.location.href = "${process.env.AQUILACMS_URL}/cart/address?jwt=${token}&cartid=${cartId}"
}
</script>
</head>
<body>
<div id="checkout"></div>
</body>
</html>
`

View File

@ -1,28 +1,8 @@
import type { GetLoggedInCustomerQuery } from '../../../schema'
import type { CustomersHandlers } from '..'
import { normalizeUser } from '../../../lib/normalize'
import type { AquilacmsUser, User } from '../../../types'
export const getLoggedInCustomerQuery = /* GraphQL */ `
query getLoggedInCustomer {
customer {
entityId
firstName
lastName
email
company
customerGroupId
notes
phone
addressCount
attributeCount
storeCredit {
value
currencyCode
}
}
}
`
export type Customer = NonNullable<GetLoggedInCustomerQuery['customer']>
export type Customer = User
const getLoggedInCustomer: CustomersHandlers['getLoggedInCustomer'] = async ({
req,
@ -32,25 +12,27 @@ const getLoggedInCustomer: CustomersHandlers['getLoggedInCustomer'] = async ({
const token = req.cookies[config.customerCookie]
if (token) {
const { data } = await config.fetch<GetLoggedInCustomerQuery>(
getLoggedInCustomerQuery,
undefined,
{
try {
const data = await config.storeApiFetch('/v2/user', {
method: 'POST',
body: JSON.stringify({
PostBody: {},
}),
headers: {
cookie: `${config.customerCookie}=${token}`,
authorization: token,
},
}
)
const { customer } = data
if (!customer) {
})
if (!data) {
return res.status(400).json({
data: null,
errors: [{ message: 'Customer not found', code: 'not_found' }],
})
}
const customer = normalizeUser(data as AquilacmsUser)
return res.status(200).json({ data: { customer } })
} catch (err) {
console.error(err)
}
}
res.status(200).json({ data: null })

View File

@ -1,4 +1,5 @@
import { serialize } from 'cookie'
import { getConfig } from '../..'
import { LogoutHandlers } from '../logout'
const logoutHandler: LogoutHandlers['logout'] = async ({
@ -6,6 +7,12 @@ const logoutHandler: LogoutHandlers['logout'] = async ({
body: { redirectTo },
config,
}) => {
config = getConfig(config)
await config.storeApiFetch('/v2/auth/logout', {
method: 'GET',
})
// Remove the cookie
res.setHeader(
'Set-Cookie',

View File

@ -1,36 +1,49 @@
import { AquilacmsApiError } from '../../utils/errors'
import login from '../../../auth/login'
import { SignupHandlers } from '../signup'
import Joi, { valid } from 'joi'
const signup: SignupHandlers['signup'] = async ({
res,
body: { firstName, lastName, email, password },
config,
}) => {
// TODO: Add proper validations with something like Ajv
const schema = Joi.object({
firstName: Joi.string().min(1),
lastName: Joi.string().min(1),
email: Joi.string().email({ tlds: false }),
password: Joi.string().pattern(
new RegExp('^(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^wd:])([^s]){6,}$')
),
})
const validation = schema.validate({ email, password })
if (!(firstName && lastName && email && password)) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
// TODO: validate the password and email
// Passwords must be at least 7 characters and contain both alphabetic
// and numeric characters.
if (validation?.error?.details) {
let message = validation.error.details[0].message
if (validation.error.details[0].path[0] === 'password')
message =
'password must have a lowercase, a uppercase, a number and be at least 6 characters long'
return res.status(400).json({
data: null,
errors: [{ message }],
})
}
try {
await config.storeApiFetch('/v3/customers', {
method: 'POST',
body: JSON.stringify([
{
first_name: firstName,
last_name: lastName,
await config.storeApiFetch('/v2/user', {
method: 'PUT',
body: JSON.stringify({
firstname: firstName,
lastname: lastName,
email,
authentication: {
new_password: password,
},
},
]),
password,
}),
})
} catch (error) {
if (error instanceof AquilacmsApiError && error.status === 422) {

File diff suppressed because it is too large Load Diff

View File

@ -1,329 +0,0 @@
/**
* This file was auto-generated by swagger-to-ts.
* Do not make direct changes to the file.
*/
export interface definitions {
blogPost_Full: {
/**
* ID of this blog post. (READ-ONLY)
*/
id?: number
} & definitions['blogPost_Base']
addresses: {
/**
* Full URL of where the resource is located.
*/
url?: string
/**
* Resource being accessed.
*/
resource?: string
}
formField: {
/**
* Name of the form field
*/
name?: string
/**
* Value of the form field
*/
value?: string
}
page_Full: {
/**
* ID of the page.
*/
id?: number
} & definitions['page_Base']
redirect: {
/**
* Numeric ID of the redirect.
*/
id?: number
/**
* The path from which to redirect.
*/
path: string
forward: definitions['forward']
/**
* URL of the redirect. READ-ONLY
*/
url?: string
}
forward: {
/**
* The type of redirect. If it is a `manual` redirect then type will always be manual. Dynamic redirects will have the type of the page. Such as product or category.
*/
type?: string
/**
* Reference of the redirect. Dynamic redirects will have the category or product number. Manual redirects will have the url that is being directed to.
*/
ref?: number
}
customer_Full: {
/**
* Unique numeric ID of this customer. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
id?: number
/**
* Not returned in any responses, but accepts up to two fields allowing you to set the customers password. If a password is not supplied, it is generated automatically. For further information about using this object, please see the Customers resource documentation.
*/
_authentication?: {
force_reset?: string
password?: string
password_confirmation?: string
}
/**
* The name of the company for which the customer works.
*/
company?: string
/**
* First name of the customer.
*/
first_name: string
/**
* Last name of the customer.
*/
last_name: string
/**
* Email address of the customer.
*/
email: string
/**
* Phone number of the customer.
*/
phone?: string
/**
* Date on which the customer registered from the storefront or was created in the control panel. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
date_created?: string
/**
* Date on which the customer updated their details in the storefront or was updated in the control panel. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
date_modified?: string
/**
* The amount of credit the customer has. (Float, Float as String, Integer)
*/
store_credit?: string
/**
* The customers IP address when they signed up.
*/
registration_ip_address?: string
/**
* The group to which the customer belongs.
*/
customer_group_id?: number
/**
* Store-owner notes on the customer.
*/
notes?: string
/**
* Used to identify customers who fall into special sales-tax categories in particular, those who are fully or partially exempt from paying sales tax. Can be blank, or can contain a single AvaTax code. (The codes are case-sensitive.) Stores that subscribe to BigCommerces Avalara Premium integration will use this code to determine how/whether to apply sales tax. Does not affect sales-tax calculations for stores that do not subscribe to Avalara Premium.
*/
tax_exempt_category?: string
/**
* Records whether the customer would like to receive marketing content from this store. READ-ONLY.This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
accepts_marketing?: boolean
addresses?: definitions['addresses']
/**
* Array of custom fields. This is a READ-ONLY field; do not set or modify its value in a POST or PUT request.
*/
form_fields?: definitions['formField'][]
/**
* Force a password change on next login.
*/
reset_pass_on_login?: boolean
}
categoryAccessLevel: {
/**
* + `all` - Customers can access all categories
* + `specific` - Customers can access a specific list of categories
* + `none` - Customers are prevented from viewing any of the categories in this group.
*/
type?: 'all' | 'specific' | 'none'
/**
* Is an array of category IDs and should be supplied only if `type` is specific.
*/
categories?: string[]
}
timeZone: {
/**
* a string identifying the time zone, in the format: <Continent-name>/<City-name>.
*/
name?: string
/**
* a negative or positive number, identifying the offset from UTC/GMT, in seconds, during winter/standard time.
*/
raw_offset?: number
/**
* "-/+" offset from UTC/GMT, in seconds, during summer/daylight saving time.
*/
dst_offset?: number
/**
* a boolean indicating whether this time zone observes daylight saving time.
*/
dst_correction?: boolean
date_format?: definitions['dateFormat']
}
count_Response: { count?: number }
dateFormat: {
/**
* string that defines dates display format, in the pattern: M jS Y
*/
display?: string
/**
* string that defines the CSV export format for orders, customers, and products, in the pattern: M jS Y
*/
export?: string
/**
* string that defines dates extended-display format, in the pattern: M jS Y @ g:i A.
*/
extended_display?: string
}
blogTags: { tag?: string; post_ids?: number[] }[]
blogPost_Base: {
/**
* Title of this blog post.
*/
title: string
/**
* URL for the public blog post.
*/
url?: string
/**
* URL to preview the blog post. (READ-ONLY)
*/
preview_url?: string
/**
* Text body of the blog post.
*/
body: string
/**
* Tags to characterize the blog post.
*/
tags?: string[]
/**
* Summary of the blog post. (READ-ONLY)
*/
summary?: string
/**
* Whether the blog post is published.
*/
is_published?: boolean
published_date?: definitions['publishedDate']
/**
* Published date in `ISO 8601` format.
*/
published_date_iso8601?: string
/**
* Description text for this blog posts `<meta/>` element.
*/
meta_description?: string
/**
* Keywords for this blog posts `<meta/>` element.
*/
meta_keywords?: string
/**
* Name of the blog posts author.
*/
author?: string
/**
* Local path to a thumbnail uploaded to `product_images/` via [WebDav](https://support.bigcommerce.com/s/article/File-Access-WebDAV).
*/
thumbnail_path?: string
}
publishedDate: { timezone_type?: string; date?: string; timezone?: string }
/**
* Not returned in any responses, but accepts up to two fields allowing you to set the customers password. If a password is not supplied, it is generated automatically. For further information about using this object, please see the Customers resource documentation.
*/
authentication: {
force_reset?: string
password?: string
password_confirmation?: string
}
customer_Base: { [key: string]: any }
page_Base: {
/**
* ID of any parent Web page.
*/
parent_id?: number
/**
* `page`: free-text page
* `link`: link to another web address
* `rss_feed`: syndicated content from an RSS feed
* `contact_form`: When the store's contact form is used.
*/
type: 'page' | 'rss_feed' | 'contact_form' | 'raw' | 'link'
/**
* Where the pages type is a contact form: object whose members are the fields enabled (in the control panel) for storefront display. Possible members are:`fullname`: full name of the customer submitting the form; `phone`: customers phone number, as submitted on the form; `companyname`: customers submitted company name; `orderno`: customers submitted order number; `rma`: customers submitted RMA (Return Merchandise Authorization) number.
*/
contact_fields?: string
/**
* Where the pages type is a contact form: email address that receives messages sent via the form.
*/
email?: string
/**
* Page name, as displayed on the storefront.
*/
name: string
/**
* Relative URL on the storefront for this page.
*/
url?: string
/**
* Description contained within this pages `<meta/>` element.
*/
meta_description?: string
/**
* HTML or variable that populates this pages `<body>` element, in default/desktop view. Required in POST if page type is `raw`.
*/
body: string
/**
* HTML to use for this page's body when viewed in the mobile template (deprecated).
*/
mobile_body?: string
/**
* If true, this page has a mobile version.
*/
has_mobile_version?: boolean
/**
* If true, this page appears in the storefronts navigation menu.
*/
is_visible?: boolean
/**
* If true, this page is the storefronts home page.
*/
is_homepage?: boolean
/**
* Text specified for this pages `<title>` element. (If empty, the value of the name property is used.)
*/
meta_title?: string
/**
* Layout template for this page. This field is writable only for stores with a Blueprint theme applied.
*/
layout_file?: string
/**
* Order in which this page should display on the storefront. (Lower integers specify earlier display.)
*/
sort_order?: number
/**
* Comma-separated list of keywords that shoppers can use to locate this page when searching the store.
*/
search_keywords?: string
/**
* Comma-separated list of SEO-relevant keywords to include in the pages `<meta/>` element.
*/
meta_keywords?: string
/**
* If page type is `rss_feed` the n this field is visisble. Required in POST required for `rss page` type.
*/
feed: string
/**
* If page type is `link` this field is returned. Required in POST to create a `link` page.
*/
link: string
content_type?: 'application/json' | 'text/javascript' | 'text/html'
}
}

View File

@ -1,142 +0,0 @@
/**
* This file was auto-generated by swagger-to-ts.
* Do not make direct changes to the file.
*/
export interface definitions {
wishlist_Post: {
/**
* The customer id.
*/
customer_id: number
/**
* Whether the wishlist is available to the public.
*/
is_public?: boolean
/**
* The title of the wishlist.
*/
name?: string
/**
* Array of Wishlist items.
*/
items?: {
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the product.
*/
variant_id?: number
}[]
}
wishlist_Put: {
/**
* The customer id.
*/
customer_id: number
/**
* Whether the wishlist is available to the public.
*/
is_public?: boolean
/**
* The title of the wishlist.
*/
name?: string
/**
* Array of Wishlist items.
*/
items?: {
/**
* The ID of the item
*/
id?: number
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the item.
*/
variant_id?: number
}[]
}
wishlist_Full: {
/**
* Wishlist ID, provided after creating a wishlist with a POST.
*/
id?: number
/**
* The ID the customer to which the wishlist belongs.
*/
customer_id?: number
/**
* The Wishlist's name.
*/
name?: string
/**
* Whether the Wishlist is available to the public.
*/
is_public?: boolean
/**
* The token of the Wishlist. This is created internally within BigCommerce. The Wishlist ID is to be used for external apps. Read-Only
*/
token?: string
/**
* Array of Wishlist items
*/
items?: definitions['wishlistItem_Full'][]
}
wishlistItem_Full: {
/**
* The ID of the item
*/
id?: number
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the item.
*/
variant_id?: number
}
wishlistItem_Post: {
/**
* The ID of the product.
*/
product_id?: number
/**
* The variant ID of the product.
*/
variant_id?: number
}
/**
* Data about the response, including pagination and collection totals.
*/
pagination: {
/**
* Total number of items in the result set.
*/
total?: number
/**
* Total number of items in the collection response.
*/
count?: number
/**
* The amount of items returned in the collection per page, controlled by the limit parameter.
*/
per_page?: number
/**
* The page you are currently on within the collection.
*/
current_page?: number
/**
* The total number of pages in the collection.
*/
total_pages?: number
}
error: { status?: number; title?: string; type?: string }
metaCollection: { pagination?: definitions['pagination'] }
}

View File

@ -1,9 +0,0 @@
export const categoryTreeItemFragment = /* GraphQL */ `
fragment categoryTreeItem on CategoryTreeItem {
entityId
name
path
description
productCount
}
`

View File

@ -1,113 +0,0 @@
export const productPrices = /* GraphQL */ `
fragment productPrices on Prices {
price {
value
currencyCode
}
salePrice {
value
currencyCode
}
retailPrice {
value
currencyCode
}
}
`
export const swatchOptionFragment = /* GraphQL */ `
fragment swatchOption on SwatchOptionValue {
isDefault
hexColors
}
`
export const multipleChoiceOptionFragment = /* GraphQL */ `
fragment multipleChoiceOption on MultipleChoiceOption {
values {
edges {
node {
label
...swatchOption
}
}
}
}
${swatchOptionFragment}
`
export const productInfoFragment = /* GraphQL */ `
fragment productInfo on Product {
entityId
name
path
brand {
entityId
}
description
prices {
...productPrices
}
images {
edges {
node {
urlOriginal
altText
isDefault
}
}
}
variants {
edges {
node {
entityId
defaultImage {
urlOriginal
altText
isDefault
}
}
}
}
productOptions {
edges {
node {
__typename
entityId
displayName
...multipleChoiceOption
}
}
}
localeMeta: metafields(namespace: $locale, keys: ["name", "description"])
@include(if: $hasLocale) {
edges {
node {
key
value
}
}
}
}
${productPrices}
${multipleChoiceOptionFragment}
`
export const productConnectionFragment = /* GraphQL */ `
fragment productConnnection on ProductConnection {
pageInfo {
startCursor
endCursor
}
edges {
cursor
node {
...productInfo
}
}
}
${productInfoFragment}
`

View File

@ -29,13 +29,8 @@ if (!STORE_API_URL) {
export class Config {
private config: AquilacmsConfig
constructor(config: Omit<AquilacmsConfig, 'customerCookie'>) {
this.config = {
...config,
// The customerCookie is not customizable for now, BC sets the cookie and it's
// not important to rename it
customerCookie: 'SHOP_TOKEN',
}
constructor(config: AquilacmsConfig) {
this.config = config
}
getConfig(userConfig: Partial<AquilacmsConfig> = {}) {
@ -60,6 +55,7 @@ const config = new Config({
applyLocale: true,
storeApiUrl: STORE_API_URL,
storeApiFetch: fetchStoreApi,
customerCookie: 'jwt',
})
export function getConfig(userConfig?: Partial<AquilacmsConfig>) {

View File

@ -16,8 +16,6 @@ export default async function fetchStoreApi<T>(
headers: {
...options?.headers,
'Content-Type': 'application/json',
'X-Auth-Token': config.storeApiToken,
'X-Auth-Client': config.storeApiClientId,
},
})
} catch (error) {
@ -32,7 +30,7 @@ export default async function fetchStoreApi<T>(
if (!res.ok) {
const data = isJSON ? await res.json() : await getTextOrNull(res)
const headers = getRawHeaders(res)
const msg = `Big Commerce API error (${
const msg = `Aquilacms API error (${
res.status
}) \nHeaders: ${JSON.stringify(headers, null, 2)}\n${
typeof data === 'string' ? data : JSON.stringify(data, null, 2)
@ -40,7 +38,6 @@ export default async function fetchStoreApi<T>(
throw new AquilacmsApiError(msg, res, data)
}
if (res.status !== 204 && !isJSON) {
throw new AquilacmsApiError(
`Fetch to Aquilacms API failed, expected JSON content but found: ${contentType}`,

View File

@ -1,5 +0,0 @@
export default function filterEdges<T>(
edges: (T | null | undefined)[] | null | undefined
) {
return edges?.filter((edge): edge is T => !!edge) ?? []
}

View File

@ -1,28 +0,0 @@
import type { ItemBody as WishlistItemBody } from '../wishlist'
import type { CartItemBody, OptionSelections } from '../../types'
type BCWishlistItemBody = {
product_id: number
variant_id: number
}
type BCCartItemBody = {
product_id: number
variant_id: number
quantity?: number
option_selections?: OptionSelections
}
export const parseWishlistItem = (
item: WishlistItemBody
): BCWishlistItemBody => ({
product_id: Number(item.productId),
variant_id: Number(item.variantId),
})
export const parseCartItem = (item: CartItemBody): BCCartItemBody => ({
quantity: item.quantity,
product_id: Number(item.productId),
variant_id: Number(item.variantId),
option_selections: item.optionSelections,
})

View File

@ -1,21 +0,0 @@
import type { ProductNode } from '../../product/get-all-products'
import type { RecursivePartial } from './types'
export default function setProductLocaleMeta(
node: RecursivePartial<ProductNode>
) {
if (node.localeMeta?.edges) {
node.localeMeta.edges = node.localeMeta.edges.filter((edge) => {
const { key, value } = edge?.node ?? {}
if (key && key in node) {
;(node as any)[key] = value
return false
}
return true
})
if (!node.localeMeta.edges.length) {
delete node.localeMeta
}
}
}

View File

@ -1,56 +0,0 @@
import type { WishlistHandlers } from '..'
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import { parseWishlistItem } from '../../utils/parse-item'
// Returns the wishlist of the signed customer
const addItem: WishlistHandlers['addItem'] = async ({
res,
body: { customerToken, item },
config,
}) => {
if (!item) {
return res.status(400).json({
data: null,
errors: [{ message: 'Missing item' }],
})
}
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
if (!customerId) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const { wishlist } = await getCustomerWishlist({
variables: { customerId },
config,
})
const options = {
method: 'POST',
body: JSON.stringify(
wishlist
? {
items: [parseWishlistItem(item)],
}
: {
name: 'Wishlist',
customer_id: customerId,
items: [parseWishlistItem(item)],
is_public: false,
}
),
}
const { data } = wishlist
? await config.storeApiFetch(`/v3/wishlists/${wishlist.id}/items`, options)
: await config.storeApiFetch('/v3/wishlists', options)
res.status(200).json({ data })
}
export default addItem

View File

@ -1,37 +0,0 @@
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerWishlist from '../../../customer/get-customer-wishlist'
import type { Wishlist, WishlistHandlers } from '..'
// Return wishlist info
const getWishlist: WishlistHandlers['getWishlist'] = async ({
res,
body: { customerToken, includeProducts },
config,
}) => {
let result: { data?: Wishlist } = {}
if (customerToken) {
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
if (!customerId) {
// If the customerToken is invalid, then this request is too
return res.status(404).json({
data: null,
errors: [{ message: 'Wishlist not found' }],
})
}
const { wishlist } = await getCustomerWishlist({
variables: { customerId },
includeProducts,
config,
})
result = { data: wishlist }
}
res.status(200).json({ data: result.data ?? null })
}
export default getWishlist

View File

@ -1,39 +0,0 @@
import getCustomerId from '../../../customer/get-customer-id'
import getCustomerWishlist, {
Wishlist,
} from '../../../customer/get-customer-wishlist'
import type { WishlistHandlers } from '..'
// Return current wishlist info
const removeItem: WishlistHandlers['removeItem'] = async ({
res,
body: { customerToken, itemId },
config,
}) => {
const customerId =
customerToken && (await getCustomerId({ customerToken, config }))
const { wishlist } =
(customerId &&
(await getCustomerWishlist({
variables: { customerId },
config,
}))) ||
{}
if (!wishlist || !itemId) {
return res.status(400).json({
data: null,
errors: [{ message: 'Invalid request' }],
})
}
const result = await config.storeApiFetch<{ data: Wishlist } | null>(
`/v3/wishlists/${wishlist.id}/items/${itemId}`,
{ method: 'DELETE' }
)
const data = result?.data ?? null
res.status(200).json({ data })
}
export default removeItem

View File

@ -1,104 +0,0 @@
import isAllowedMethod from '../utils/is-allowed-method'
import createApiHandler, {
AquilacmsApiHandler,
AquilacmsHandler,
} from '../utils/create-api-handler'
import { AquilacmsApiError } from '../utils/errors'
import type {
Wishlist,
WishlistItem,
} from '../../customer/get-customer-wishlist'
import getWishlist from './handlers/get-wishlist'
import addItem from './handlers/add-item'
import removeItem from './handlers/remove-item'
import type { Product, ProductVariant, Customer } from '@commerce/types'
export type { Wishlist, WishlistItem }
export type ItemBody = {
productId: Product['id']
variantId: ProductVariant['id']
}
export type AddItemBody = { item: ItemBody }
export type RemoveItemBody = { itemId: Product['id'] }
export type WishlistBody = {
customer_id: Customer['entityId']
is_public: number
name: string
items: any[]
}
export type AddWishlistBody = { wishlist: WishlistBody }
export type WishlistHandlers = {
getWishlist: AquilacmsHandler<
Wishlist,
{ customerToken?: string; includeProducts?: boolean }
>
addItem: AquilacmsHandler<
Wishlist,
{ customerToken?: string } & Partial<AddItemBody>
>
removeItem: AquilacmsHandler<
Wishlist,
{ customerToken?: string } & Partial<RemoveItemBody>
>
}
const METHODS = ['GET', 'POST', 'DELETE']
// TODO: a complete implementation should have schema validation for `req.body`
const wishlistApi: AquilacmsApiHandler<Wishlist, WishlistHandlers> = async (
req,
res,
config,
handlers
) => {
if (!isAllowedMethod(req, res, METHODS)) return
const { cookies } = req
const customerToken = cookies[config.customerCookie]
try {
// Return current wishlist info
if (req.method === 'GET') {
const body = {
customerToken,
includeProducts: req.query.products === '1',
}
return await handlers['getWishlist']({ req, res, config, body })
}
// Add an item to the wishlist
if (req.method === 'POST') {
const body = { ...req.body, customerToken }
return await handlers['addItem']({ req, res, config, body })
}
// Remove an item from the wishlist
if (req.method === 'DELETE') {
const body = { ...req.body, customerToken }
return await handlers['removeItem']({ req, res, config, body })
}
} catch (error) {
console.error(error)
const message =
error instanceof AquilacmsApiError
? 'An unexpected error ocurred with the Aquilacms API'
: 'An unexpected error ocurred'
res.status(500).json({ data: null, errors: [{ message }] })
}
}
export const handlers = {
getWishlist,
addItem,
removeItem,
}
export default createApiHandler(wishlistApi, handlers, {})

View File

@ -1,20 +1,11 @@
import type { ServerResponse } from 'http'
import type { LoginMutation, LoginMutationVariables } from '../schema'
import type { RecursivePartial } from '../api/utils/types'
import concatHeader from '../api/utils/concat-cookie'
import { AquilacmsConfig, getConfig } from '../api'
export const loginMutation = /* GraphQL */ `
mutation login($email: String!, $password: String!) {
login(email: $email, password: $password) {
result
}
}
`
import { serialize } from 'cookie'
export type LoginResult<T extends { result?: any } = { result?: string }> = T
export type LoginVariables = LoginMutationVariables
export type LoginVariables = { email: string; password: string }
async function login(opts: {
variables: LoginVariables
@ -30,7 +21,6 @@ async function login<T extends { result?: any }, V = any>(opts: {
}): Promise<LoginResult<T>>
async function login({
query = loginMutation,
variables,
res: response,
config,
@ -42,31 +32,24 @@ async function login({
}): Promise<LoginResult> {
config = getConfig(config)
const { data, res } = await config.fetch<RecursivePartial<LoginMutation>>(
query,
{ variables }
)
// Bigcommerce returns a Set-Cookie header with the auth cookie
let cookie = res.headers.get('Set-Cookie')
if (cookie && typeof cookie === 'string') {
// In development, don't set a secure cookie or the browser will ignore it
if (process.env.NODE_ENV !== 'production') {
cookie = cookie.replace('; Secure', '')
// SameSite=none can't be set unless the cookie is Secure
// bc seems to sometimes send back SameSite=None rather than none so make
// this case insensitive
cookie = cookie.replace(/; SameSite=none/gi, '; SameSite=lax')
}
const { data, code: result } = await config.storeApiFetch('/v2/auth/login', {
method: 'POST',
body: JSON.stringify({
username: variables.email,
password: variables.password,
}),
})
response.setHeader(
'Set-Cookie',
concatHeader(response.getHeader('Set-Cookie'), cookie)!
concatHeader(
response.getHeader('Set-Cookie'),
serialize(config.customerCookie, data, { sameSite: 'lax', path: '/' })
)!
)
}
return {
result: data.login?.result,
result,
}
}

View File

@ -3,12 +3,7 @@ import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useAddItem, { UseAddItem } from '@commerce/cart/use-add-item'
import { normalizeCart } from '../lib/normalize'
import type {
Cart,
AquilacmsCart,
CartItemBody,
AddCartItemBody,
} from '../types'
import type { Cart, CartItemBody, AddCartItemBody } from '../types'
import useCart from './use-cart'
export default useAddItem as UseAddItem<typeof handler>
@ -28,12 +23,13 @@ export const handler: MutationHook<Cart, {}, CartItemBody> = {
})
}
const data = await fetch<AquilacmsCart, AddCartItemBody>({
const data = await fetch<Cart, AddCartItemBody>({
...options,
body: { item },
})
return normalizeCart(data)
// return normalizeCart(data)
return data
},
useHook: ({ fetch }) => () => {
const { mutate } = useCart()

View File

@ -18,7 +18,7 @@ export const handler: SWRHook<
},
async fetcher({ input: { cartId }, options, fetch }) {
const data = cartId ? await fetch(options) : null
return data && normalizeCart(data)
return data // && normalizeCart(data)
},
useHook: ({ useData }) => (input) => {
const response = useData({

View File

@ -41,7 +41,8 @@ export const handler = {
...options,
body: { itemId },
})
return normalizeCart(data)
// return normalizeCart(data)
return data
},
useHook: ({
fetch,

View File

@ -55,7 +55,8 @@ export const handler = {
body: { itemId, item },
})
return normalizeCart(data)
// return normalizeCart(data)
return data
},
useHook: ({
fetch,

View File

@ -1,6 +1,7 @@
{
"provider": "aquilacms",
"features": {
"wishlist": false
"wishlist": false,
"customCheckout": true
}
}

View File

@ -1,8 +1,13 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { AquilacmsConfig, getConfig } from '../api'
import { definitions } from '../api/definitions/store-content'
import type { AquilacmsStatic } from '../types'
export type Page = definitions['page_Full']
export type Page = {
id: string
name: string
url: string
sort_order?: number
body: string
}
export type GetAllPagesResult<
T extends { pages: any[] } = { pages: Page[] }
@ -28,15 +33,42 @@ async function getAllPages({
preview?: boolean
} = {}): Promise<GetAllPagesResult> {
config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is
// required in case there's a custom `url`
const { data } = await config.storeApiFetch<
RecursivePartial<{ data: Page[] }>
>('/v3/content/pages')
const pages = (data as RecursiveRequired<typeof data>) ?? []
// const { datas } = await config.storeApiFetch('/v2/categories', {
// method: 'POST',
// body: JSON.stringify({
// lang: 'en',
// PostBody: {
// filter: {
// action: 'page',
// },
// limit: 10,
// page: 1,
// },
// }),
// })
const { datas }: { datas: AquilacmsStatic[] } = await config.storeApiFetch(
'/v2/statics',
{
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
limit: 10,
page: 1,
},
}),
}
)
const pages: Page[] = datas.map((s: AquilacmsStatic) => ({
id: `en-US/${s._id}`,
name: s.slug['en'],
url: `/en-US/${s.slug['en']}`,
body: s.content,
}))
return {
pages: preview ? pages : pages.filter((p) => p.is_visible),
pages,
}
}

View File

@ -1,13 +1,11 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { AquilacmsConfig, getConfig } from '../api'
import { definitions } from '../api/definitions/store-content'
export type Page = definitions['page_Full']
import { Page } from './get-all-pages'
import type { AquilacmsStatic } from '../types'
export type GetPageResult<T extends { page?: any } = { page?: Page }> = T
export type PageVariables = {
id: number
id: string
}
async function getPage(opts: {
@ -26,7 +24,7 @@ async function getPage<T extends { page?: any }, V = any>(opts: {
async function getPage({
url,
variables,
variables: { id },
config,
preview,
}: {
@ -36,18 +34,42 @@ async function getPage({
preview?: boolean
}): Promise<GetPageResult> {
config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is
// required in case there's a custom `url`
const { data } = await config.storeApiFetch<
RecursivePartial<{ data: Page[] }>
>(url || `/v3/content/pages?id=${variables.id}&include=body`)
const firstPage = data?.[0]
const page = firstPage as RecursiveRequired<typeof firstPage>
const [locale, _id] = id.split('/')
const lang = locale.split('-')[0]
// const page: any = await config.storeApiFetch('/v2/category', {
// method: 'POST',
// body: JSON.stringify({
// lang,
// PostBody: {
// filter: {
// action: 'page',
// _id,
// },
// limit: 10,
// page: 1,
// },
// }),
// })
const staticPage: AquilacmsStatic = await config.storeApiFetch('/v2/static', {
method: 'POST',
body: JSON.stringify({
lang,
PostBody: {
filter: {
_id,
},
},
}),
})
if (preview || page?.is_visible) {
return { page }
return {
page: {
id: `${locale}/${staticPage._id}`,
name: staticPage.slug[lang],
url: `/${locale}/${staticPage.slug[lang]}`,
body: staticPage?.content ?? '',
},
}
return {}
}
export default getPage

View File

@ -1,105 +1,56 @@
import type { GetSiteInfoQuery, GetSiteInfoQueryVariables } from '../schema'
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import filterEdges from '../api/utils/filter-edges'
import { AquilacmsConfig, getConfig } from '../api'
import { categoryTreeItemFragment } from '../api/fragments/category-tree'
// Get 3 levels of categories
export const getSiteInfoQuery = /* GraphQL */ `
query getSiteInfo {
site {
categoryTree {
...categoryTreeItem
children {
...categoryTreeItem
children {
...categoryTreeItem
}
}
}
brands {
pageInfo {
startCursor
endCursor
}
edges {
cursor
node {
entityId
name
defaultImage {
urlOriginal
altText
}
pageTitle
metaDesc
metaKeywords
searchKeywords
path
}
}
}
}
}
${categoryTreeItemFragment}
`
export type CategoriesTree = NonNullable<
GetSiteInfoQuery['site']['categoryTree']
>
export type BrandEdge = NonNullable<
NonNullable<GetSiteInfoQuery['site']['brands']['edges']>[0]
>
export type Brands = BrandEdge[]
export type GetSiteInfoResult<
T extends { categories: any[]; brands: any[] } = {
categories: CategoriesTree
brands: Brands
}
> = T
export type GetSiteInfoResult = { categories: any[]; brands: any[] }
async function getSiteInfo(opts?: {
variables?: GetSiteInfoQueryVariables
variables?: any
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetSiteInfoResult>
async function getSiteInfo<
T extends { categories: any[]; brands: any[] },
V = any
>(opts: {
query: string
async function getSiteInfo<T extends GetSiteInfoResult, V = any>(opts: {
variables?: V
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetSiteInfoResult<T>>
}): Promise<GetSiteInfoResult>
async function getSiteInfo({
query = getSiteInfoQuery,
variables,
config,
}: {
query?: string
variables?: GetSiteInfoQueryVariables
variables?: any
config?: AquilacmsConfig
preview?: boolean
} = {}): Promise<GetSiteInfoResult> {
// TODO:
config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is
// required in case there's a custom `query`
const { data } = await config.fetch<RecursivePartial<GetSiteInfoQuery>>(
query,
{ variables }
)
const categories = data.site?.categoryTree
const brands = data.site?.brands?.edges
const { datas } = await config.storeApiFetch('/v2/categories', {
method: 'POST',
body: JSON.stringify({
lang: 'en',
PostBody: {
filter: {
action: 'catalog',
},
limit: 10,
page: 1,
structure: {
code: 1,
slug: 1,
name: 1,
},
},
}),
})
return {
categories: (categories as RecursiveRequired<typeof categories>) ?? [],
brands: filterEdges(brands as RecursiveRequired<typeof brands>),
categories: datas.map((c: any) => ({
path: c.slug['en'],
entityId: c._id,
name: c.name,
})),
brands: [],
}
}

View File

@ -1,13 +1,5 @@
import { GetCustomerIdQuery } from '../schema'
import { AquilacmsConfig, getConfig } from '../api'
export const getCustomerIdQuery = /* GraphQL */ `
query getCustomerId {
customer {
entityId
}
}
`
import { AquilacmsUser } from '../types'
async function getCustomerId({
customerToken,
@ -15,20 +7,19 @@ async function getCustomerId({
}: {
customerToken: string
config?: AquilacmsConfig
}): Promise<number | undefined> {
}): Promise<string | undefined> {
config = getConfig(config)
const { data } = await config.fetch<GetCustomerIdQuery>(
getCustomerIdQuery,
undefined,
{
const data: AquilacmsUser = await config.storeApiFetch('/v2/user', {
method: 'POST',
body: JSON.stringify({
PostBody: {},
}),
headers: {
cookie: `${config.customerCookie}=${customerToken}`,
authorization: customerToken,
},
}
)
})
return data?.customer?.entityId
return data._id
}
export default getCustomerId

View File

@ -1,88 +0,0 @@
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import { definitions } from '../api/definitions/wishlist'
import { AquilacmsConfig, getConfig } from '../api'
import getAllProducts, { ProductEdge } from '../product/get-all-products'
export type Wishlist = Omit<definitions['wishlist_Full'], 'items'> & {
items?: WishlistItem[]
}
export type WishlistItem = NonNullable<
definitions['wishlist_Full']['items']
>[0] & {
product?: ProductEdge['node']
}
export type GetCustomerWishlistResult<
T extends { wishlist?: any } = { wishlist?: Wishlist }
> = T
export type GetCustomerWishlistVariables = {
customerId: number
}
async function getCustomerWishlist(opts: {
variables: GetCustomerWishlistVariables
config?: AquilacmsConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult>
async function getCustomerWishlist<
T extends { wishlist?: any },
V = any
>(opts: {
url: string
variables: V
config?: AquilacmsConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult<T>>
async function getCustomerWishlist({
config,
variables,
includeProducts,
}: {
url?: string
variables: GetCustomerWishlistVariables
config?: AquilacmsConfig
includeProducts?: boolean
}): Promise<GetCustomerWishlistResult> {
config = getConfig(config)
const { data = [] } = await config.storeApiFetch<
RecursivePartial<{ data: Wishlist[] }>
>(`/v3/wishlists?customer_id=${variables.customerId}`)
const wishlist = data[0]
if (includeProducts && wishlist?.items?.length) {
const entityIds = wishlist.items
?.map((item) => item?.product_id)
.filter((id): id is number => !!id)
if (entityIds?.length) {
const graphqlData = await getAllProducts({
variables: { first: 100, entityIds },
config,
})
// Put the products in an object that we can use to get them by id
const productsById = graphqlData.products.reduce<{
[k: number]: ProductEdge
}>((prods, p) => {
prods[Number(p.id)] = p as any
return prods
}, {})
// Populate the wishlist items with the graphql products
wishlist.items.forEach((item) => {
const product = item && productsById[item.product_id!]
if (item && product) {
// @ts-ignore Fix this type when the wishlist type is properly defined
item.product = product
}
})
}
}
return { wishlist: wishlist as RecursiveRequired<typeof wishlist> }
}
export default getCustomerWishlist

View File

@ -1,13 +0,0 @@
import update, { Context } from 'immutability-helper'
const c = new Context()
c.extend('$auto', function (value, object) {
return object ? c.update(object, value) : c.update({}, value)
})
c.extend('$autoArray', function (value, object) {
return object ? c.update(object, value) : c.update([], value)
})
export default c.update

View File

@ -1,113 +1,141 @@
import type { Product } from '@commerce/types'
import type { Cart, AquilacmsCart, LineItem } from '../types'
import update from './immutability'
function normalizeProductOption(productOption: any) {
const {
node: {
entityId,
values: { edges },
...rest
},
} = productOption
import type { Product, ProductOption } from '@commerce/types'
import { getConfig } from '../api'
import type {
Cart,
AquilacmsCart,
LineItem,
AquilacmsItem,
AquilacmsProduct,
AquilacmsProductImage,
AquilacmsUser,
User,
AquilacmsProductAttribute,
} from '../types'
function normalizeProductOption(
productOption: AquilacmsProductAttribute
): ProductOption {
if (productOption.type === 'color') {
return {
id: entityId,
values: edges?.map(({ node }: any) => node),
...rest,
id: productOption.id,
displayName: productOption.name,
values: [
{
label: productOption.value,
hexColors: [productOption.value],
},
],
}
} else if (productOption.type === 'multiselect') {
return {
id: productOption.id,
displayName: productOption.name,
values: productOption.values.map((opt) => ({ label: opt })),
}
} else {
return {
id: productOption.id,
displayName: productOption.name,
values: [],
}
}
}
export function normalizeProduct(productNode: any): Product {
const {
entityId: id,
productOptions,
prices,
path,
id: _,
options: _0,
} = productNode
export function normalizeProductImage(image: AquilacmsProductImage) {
return {
url: `${process.env.AQUILACMS_URL}/${image.url}`,
alt: image.alt,
}
}
return update(productNode, {
id: { $set: String(id) },
images: {
$apply: ({ edges }: any) =>
edges?.map(({ node: { urlOriginal, altText, ...rest } }: any) => ({
url: urlOriginal,
alt: altText,
...rest,
})),
},
variants: {
$apply: ({ edges }: any) =>
edges?.map(({ node: { entityId, productOptions, ...rest } }: any) => ({
id: entityId,
options: productOptions?.edges
? productOptions.edges.map(normalizeProductOption)
: [],
...rest,
})),
},
options: {
$set: productOptions.edges
? productOptions?.edges.map(normalizeProductOption)
: [],
},
brand: {
$apply: (brand: any) => (brand?.entityId ? brand?.entityId : null),
},
slug: {
$set: path?.replace(/^\/+|\/+$/g, ''),
export function normalizeProduct(productNode: AquilacmsProduct): Product {
return {
id: productNode._id,
name: productNode.name,
description: productNode.description1?.text ?? '',
slug: productNode.slug['en'],
images: productNode.images.map(normalizeProductImage),
variants: [
{
id: productNode._id,
options:
[] ??
productNode.attributes
.filter(
(attr) => ['color', 'multiselect'].indexOf(attr.type) !== -1
)
.map(normalizeProductOption),
},
],
price: {
$set: {
value: prices?.price.value,
currencyCode: prices?.price.currencyCode,
currencyCode: 'EUR',
value: productNode.price.ati.special ?? productNode.price.ati.normal,
},
},
$unset: ['entityId'],
})
options: [] ?? productNode.attributes.map(normalizeProductOption),
}
}
export function normalizeCart(data: AquilacmsCart): Cart {
const lineItems = data.items.map(normalizeLineItem)
// TODO: not good, need to change
const price = lineItems.reduce((total, item) => total + item.variant.price, 0)
return {
id: data.id,
customerId: String(data.customer_id),
email: data.email,
createdAt: data.created_time,
currency: data.currency,
taxesIncluded: data.tax_included,
lineItems: data.line_items.physical_items.map(normalizeLineItem),
lineItemsSubtotalPrice: data.base_amount,
subtotalPrice: data.base_amount + data.discount_amount,
totalPrice: data.cart_amount,
discounts: data.discounts?.map((discount) => ({
value: discount.discounted_amount,
})),
id: data._id,
customerId: data.customer?.id,
email: data.customer?.email,
createdAt: data.createdAt,
currency: { code: 'EUR' },
taxesIncluded: true,
lineItems,
lineItemsSubtotalPrice: price,
subtotalPrice: data.priceSubTotal.ati,
totalPrice: data.priceTotal.ati,
discounts: [],
}
}
function normalizeLineItem(item: any): LineItem {
function normalizeLineItem(item: AquilacmsItem): LineItem {
const image = item.id.images.find((i: any) => i.default)
return {
id: item.id,
variantId: String(item.variant_id),
productId: String(item.product_id),
id: item._id,
variantId: item.id._id,
productId: item.id._id,
name: item.name,
quantity: item.quantity,
variant: {
id: String(item.variant_id),
sku: item.sku,
id: item.id._id,
sku: item.code,
name: item.name,
image: {
url: item.image_url,
url: `${process.env.AQUILACMS_URL}/${image?.url}`,
altText: image?.alt,
},
requiresShipping: item.is_require_shipping,
price: item.sale_price,
listPrice: item.list_price,
requiresShipping: true,
price: item.price?.special?.ati ?? item.price.unit.ati,
listPrice: item.price?.special?.ati ?? item.price.unit.ati,
},
path: `${item.id.slug['en']}`,
discounts: [],
}
}
export function normalizeUser(data: AquilacmsUser): User {
return {
entityId: data._id,
firstName: data.firstname,
lastName: data.lastname,
email: data.email,
company: data?.company?.name,
customerGroupId: '',
notes: '',
phone:
data?.addresses?.[data?.delivery_address].phone ||
data?.addresses?.[data?.delivery_address].phone_mobile,
addressCount: data?.addresses?.length,
attributeCount: 0,
storeCredit: {
value: 0,
currencyCode: 'EUR',
},
path: item.url.split('/')[3],
discounts: item.discounts.map((discount: any) => ({
value: discount.discounted_amount,
})),
}
}

View File

@ -3,6 +3,6 @@ const commerce = require('./commerce.config.json')
module.exports = {
commerce,
images: {
domains: ['cdn11.bigcommerce.com'],
domains: ['recdem.hosting-ns.com', '192.168.1.138'],
},
}

View File

@ -0,0 +1,14 @@
import { AquilacmsConfig } from '..'
import { getConfig } from '../api'
async function getAllOrders({
config,
}: {
config?: AquilacmsConfig
}): Promise<{ orders: any[] }> {
config = getConfig(config)
const data: any = []
return { orders: data }
}
export default getAllOrders

View File

@ -1,71 +1,90 @@
import type {
GetAllProductPathsQuery,
GetAllProductPathsQueryVariables,
} from '../schema'
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import filterEdges from '../api/utils/filter-edges'
import { AquilacmsConfig, getConfig } from '../api'
export const getAllProductPathsQuery = /* GraphQL */ `
query getAllProductPaths($first: Int = 100) {
site {
products(first: $first) {
edges {
node {
path
export type GetAllProductsResultAquila = {
datas: any[]
count: number
min: {
et: number
ati: number
}
max: {
et: number
ati: number
}
specialPriceMin: {
et: number
ati: number
}
}
}
`
export type ProductPath = NonNullable<
NonNullable<GetAllProductPathsQuery['site']['products']['edges']>[0]
>
export type ProductPaths = ProductPath[]
export type { GetAllProductPathsQueryVariables }
export type GetAllProductPathsResult<
T extends { products: any[] } = { products: ProductPaths }
> = T
async function getAllProductPaths(opts?: {
variables?: GetAllProductPathsQueryVariables
config?: AquilacmsConfig
}): Promise<GetAllProductPathsResult>
async function getAllProductPaths<
T extends { products: any[] },
V = any
>(opts: {
query: string
variables?: V
config?: AquilacmsConfig
}): Promise<GetAllProductPathsResult<T>>
async function getAllProductPaths({
query = getAllProductPathsQuery,
variables,
config,
}: {
query?: string
variables?: GetAllProductPathsQueryVariables
config?: AquilacmsConfig
} = {}): Promise<GetAllProductPathsResult> {
config = getConfig(config)
// RecursivePartial forces the method to check for every prop in the data, which is
// required in case there's a custom `query`
const { data } = await config.fetch<
RecursivePartial<GetAllProductPathsQuery>
>(query, { variables })
const products = data.site?.products?.edges
return {
products: filterEdges(products as RecursiveRequired<typeof products>),
specialPriceMax: {
et: number
ati: number
}
}
type ProductPath = {
node: {
path: string
}
}
type ProductPaths = ProductPath[]
type GetAllProductPathsResult<
T extends { products: any[] } = { products: ProductPaths }
> = T
async function getAllProductPaths({
variables,
config,
}: {
variables?: {
locales?: string[] | undefined
}
config?: AquilacmsConfig
} = {}): Promise<GetAllProductPathsResult> {
config = getConfig(config)
let data: any = {
paths: [],
products: [],
}
try {
const result: GetAllProductsResultAquila = await config.storeApiFetch(
'/v2/products',
{
method: 'POST',
body: JSON.stringify({
PostBody: {
structure: {
translation: 1,
},
limit: 200,
page: 1,
},
}),
}
)
// if (variables?.locales) {
// for (const locale of variables?.locales) {
// for (const p of result.datas) {
// const loc = locale.split('-')[0]
// if (p.slug[loc]) data.paths.push(`/${locale}/product/${p.slug[loc]}/`)
// }
// }
// } else {
return {
products: result.datas.map((p) => {
return {
node: {
path: `/${p.slug['en']}/`,
},
}
}),
}
// }
} catch (err) {
console.error(err)
}
return data
}
export default getAllProductPaths

View File

@ -1,57 +1,7 @@
import type {
GetAllProductsQuery,
GetAllProductsQueryVariables,
} from '../schema'
import type { Product } from '@commerce/types'
import type { RecursivePartial, RecursiveRequired } from '../api/utils/types'
import filterEdges from '../api/utils/filter-edges'
import setProductLocaleMeta from '../api/utils/set-product-locale-meta'
import { productConnectionFragment } from '../api/fragments/product'
import { AquilacmsConfig, getConfig } from '../api'
import { normalizeProduct } from '../lib/normalize'
export const getAllProductsQuery = /* GraphQL */ `
query getAllProducts(
$hasLocale: Boolean = false
$locale: String = "null"
$entityIds: [Int!]
$first: Int = 10
$products: Boolean = false
$featuredProducts: Boolean = false
$bestSellingProducts: Boolean = false
$newestProducts: Boolean = false
) {
site {
products(first: $first, entityIds: $entityIds) @include(if: $products) {
...productConnnection
}
featuredProducts(first: $first) @include(if: $featuredProducts) {
...productConnnection
}
bestSellingProducts(first: $first) @include(if: $bestSellingProducts) {
...productConnnection
}
newestProducts(first: $first) @include(if: $newestProducts) {
...productConnnection
}
}
}
${productConnectionFragment}
`
export type ProductEdge = NonNullable<
NonNullable<GetAllProductsQuery['site']['products']['edges']>[0]
>
export type ProductNode = ProductEdge['node']
export type GetAllProductsResult<
T extends Record<keyof GetAllProductsResult, any[]> = {
products: ProductEdge[]
}
> = T
const FIELDS = [
'products',
'featuredProducts',
@ -65,29 +15,12 @@ export type ProductTypes =
| 'bestSellingProducts'
| 'newestProducts'
export type ProductVariables = { field?: ProductTypes } & Omit<
GetAllProductsQueryVariables,
ProductTypes | 'hasLocale'
>
async function getAllProducts(opts?: {
variables?: ProductVariables
config?: AquilacmsConfig
preview?: boolean
}): Promise<{ products: Product[] }>
async function getAllProducts<
T extends Record<keyof GetAllProductsResult, any[]>,
V = any
>(opts: {
query: string
variables?: V
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetAllProductsResult<T>>
export type ProductVariables = { field?: ProductTypes; first?: number } & {
locale?: string
hasLocale?: boolean
}
async function getAllProducts({
query = getAllProductsQuery,
variables: { field = 'products', ...vars } = {},
config,
}: {
@ -95,12 +28,11 @@ async function getAllProducts({
variables?: ProductVariables
config?: AquilacmsConfig
preview?: boolean
// TODO: fix the product type here
} = {}): Promise<{ products: Product[] | any[] }> {
config = getConfig(config)
const locale = vars.locale || config.locale
const variables: GetAllProductsQueryVariables = {
const locale = (vars.locale || config.locale)?.split('-')[0]
const variables = {
...vars,
locale,
hasLocale: !!locale,
@ -112,24 +44,31 @@ async function getAllProducts({
)
}
variables[field] = true
// RecursivePartial forces the method to check for every prop in the data, which is
// required in case there's a custom `query`
const { data } = await config.fetch<RecursivePartial<GetAllProductsQuery>>(
query,
{ variables }
)
const edges = data.site?.[field]?.edges
const products = filterEdges(edges as RecursiveRequired<typeof edges>)
if (locale && config.applyLocale) {
products.forEach((product: RecursivePartial<ProductEdge>) => {
if (product.node) setProductLocaleMeta(product.node)
let { datas } = await config.storeApiFetch('/v2/products', {
method: 'POST',
body: JSON.stringify({
lang: locale,
PostBody: {
structure: {
code: 1,
id: 1,
translation: 1,
attributes: 1,
pictos: 1,
canonical: 1,
images: 1,
},
page: 1,
limit: variables.first,
},
}),
})
}
return { products: products.map(({ node }) => normalizeProduct(node as any)) }
const products = datas.map(normalizeProduct)
return { products }
}
export default getAllProducts

View File

@ -1,92 +1,18 @@
import type { GetProductQuery, GetProductQueryVariables } from '../schema'
import setProductLocaleMeta from '../api/utils/set-product-locale-meta'
import { productInfoFragment } from '../api/fragments/product'
import { AquilacmsConfig, getConfig } from '../api'
import { normalizeProduct } from '../lib/normalize'
import type { Product } from '@commerce/types'
export const getProductQuery = /* GraphQL */ `
query getProduct(
$hasLocale: Boolean = false
$locale: String = "null"
$path: String!
) {
site {
route(path: $path) {
node {
__typename
... on Product {
...productInfo
variants {
edges {
node {
entityId
defaultImage {
urlOriginal
altText
isDefault
}
prices {
...productPrices
}
inventory {
aggregated {
availableToSell
warningLevel
}
isInStock
}
productOptions {
edges {
node {
__typename
entityId
displayName
...multipleChoiceOption
}
}
}
}
}
}
}
}
}
}
}
${productInfoFragment}
`
export type ProductNode = Extract<
GetProductQuery['site']['route']['node'],
{ __typename: 'Product' }
>
export type GetProductResult<
T extends { product?: any } = { product?: ProductNode }
> = T
import { AquilacmsProduct } from '../types'
export type ProductVariables = { locale?: string } & (
| { path: string; slug?: never }
| { path?: never; slug: string }
)
async function getProduct(opts: {
variables: ProductVariables
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetProductResult>
async function getProduct<T extends { product?: any }, V = any>(opts: {
query: string
variables: V
config?: AquilacmsConfig
preview?: boolean
}): Promise<GetProductResult<T>>
export type GetProductResult<
T extends { product?: any } = { product?: Product }
> = T
async function getProduct({
query = getProductQuery,
variables: { slug, ...vars },
config,
}: {
@ -94,28 +20,32 @@ async function getProduct({
variables: ProductVariables
config?: AquilacmsConfig
preview?: boolean
}): Promise<Product | {} | any> {
}): Promise<Product | any> {
config = getConfig(config)
const locale = vars.locale || config.locale
const variables: GetProductQueryVariables = {
...vars,
locale,
hasLocale: !!locale,
path: slug ? `/${slug}/` : vars.path!,
}
const { data } = await config.fetch<GetProductQuery>(query, { variables })
const product = data.site?.route?.node
if (product?.__typename === 'Product') {
if (locale && config.applyLocale) {
setProductLocaleMeta(product)
}
return { product: normalizeProduct(product as any) }
}
return {}
const locale = (vars.locale || config.locale)?.split('-')[0]
const data: AquilacmsProduct = await config.storeApiFetch('/v2/product', {
method: 'POST',
body: JSON.stringify({
lang: locale,
countviews: true,
withFilters: false,
PostBody: {
filter: {
[`translation.${locale}.slug`]: slug,
},
structure: {
code: 1,
id: 1,
translation: 1,
attributes: 1,
pictos: 1,
canonical: 1,
images: 1,
},
},
}),
})
return { product: normalizeProduct(data) }
}
export default getProduct

View File

@ -25,8 +25,7 @@ export const handler: SWRHook<
const url = new URL(options.url!, 'http://a')
if (search) url.searchParams.set('search', search)
if (Number.isInteger(categoryId))
url.searchParams.set('category', String(categoryId))
if (categoryId) url.searchParams.set('category', String(categoryId))
if (Number.isInteger(brandId))
url.searchParams.set('brand', String(brandId))
if (sort) url.searchParams.set('sort', sort)

View File

@ -3,10 +3,6 @@ import { handler as useAddItem } from './cart/use-add-item'
import { handler as useUpdateItem } from './cart/use-update-item'
import { handler as useRemoveItem } from './cart/use-remove-item'
import { handler as useWishlist } from './wishlist/use-wishlist'
import { handler as useWishlistAddItem } from './wishlist/use-add-item'
import { handler as useWishlistRemoveItem } from './wishlist/use-remove-item'
import { handler as useCustomer } from './customer/use-customer'
import { handler as useSearch } from './product/use-search'
@ -15,20 +11,16 @@ import { handler as useLogout } from './auth/use-logout'
import { handler as useSignup } from './auth/use-signup'
import fetcher from './fetcher'
import { Provider } from '../commerce'
export const aquilacmsProvider = {
locale: 'en-us',
cartCookie: 'aquilacms_cartId',
fetcher,
cart: { useCart, useAddItem, useUpdateItem, useRemoveItem },
wishlist: {
useWishlist,
useAddItem: useWishlistAddItem,
useRemoveItem: useWishlistRemoveItem,
},
customer: { useCustomer },
products: { useSearch },
auth: { useLogin, useLogout, useSignup },
}
} as Provider
export type AquilacmsProvider = typeof aquilacmsProvider

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +0,0 @@
/**
* Generates definitions for REST API endpoints that are being
* used by ../api using https://github.com/drwpow/swagger-to-ts
*/
const { readFileSync, promises } = require('fs')
const path = require('path')
const fetch = require('node-fetch')
const swaggerToTS = require('@manifoldco/swagger-to-ts').default
async function getSchema(filename) {
const url = `https://next-api.stoplight.io/projects/8433/files/${filename}`
const res = await fetch(url)
if (!res.ok) {
throw new Error(`Request failed with ${res.status}: ${res.statusText}`)
}
return res.json()
}
const schemas = Object.entries({
'../api/definitions/catalog.ts':
'BigCommerce_Catalog_API.oas2.yml?ref=version%2F20.930',
'../api/definitions/store-content.ts':
'BigCommerce_Store_Content_API.oas2.yml?ref=version%2F20.930',
'../api/definitions/wishlist.ts':
'BigCommerce_Wishlist_API.oas2.yml?ref=version%2F20.930',
// swagger-to-ts is not working for the schema of the cart API
// '../api/definitions/cart.ts':
// 'BigCommerce_Server_to_Server_Cart_API.oas2.yml',
})
async function writeDefinitions() {
const ops = schemas.map(async ([dest, filename]) => {
const destination = path.join(__dirname, dest)
const schema = await getSchema(filename)
const definition = swaggerToTS(schema.content, {
prettierConfig: 'package.json',
})
await promises.writeFile(destination, definition)
console.log(`✔️ Added definitions for: ${dest}`)
})
await Promise.all(ops)
}
writeDefinitions()

View File

@ -1,24 +1,361 @@
import * as Core from '@commerce/types'
export type AquilacmsCart = {
id: string
parent_id?: string
customer_id: number
email: string
currency: { code: string }
tax_included: boolean
base_amount: number
discount_amount: number
cart_amount: number
line_items: {
custom_items: any[]
digital_items: any[]
gift_certificates: any[]
physical_items: any[]
export type AquilacmsTranslation = {
[index: string]: any
}
export enum AquilacmsCartStatus {
IN_PROGRESS = 'IN_PROGRESS',
EXPIRING = 'EXPIRING',
EXPIRED = 'EXPIRED',
}
export enum AquilacmsCartOrderReceiptMethod {
DELIVERY = 'delivery',
WITHDRAWAL = 'withdrawal',
}
export enum AquilacmsCartDiscountType {
PERCENT = 'PERCENT',
PRICE = 'PRICE',
FREE_DELIVERY = 'FREE_DELIVERY',
}
export enum supplierCode {
simple = 'simple',
bundle = 'bundle',
virtual = 'virtual',
}
export enum AquilacmsUserCivility {
MAN = 0,
WOMAN = 1,
}
export enum AquilacmsItemStatus {
PROCESSING = 'PROCESSING',
DELIVERY_PROGRESS = 'DELIVERY_PROGRESS',
DELIVERY_PARTIAL_PROGRESS = 'DELIVERY_PARTIAL_PROGRESS',
RETURNED = 'RETURNED',
RETURNED_PARTIAL = 'RETURNED_PARTIAL',
}
export type AquilacmsItem = {
_id: string
id: AquilacmsProduct
status: AquilacmsItemStatus
name: string
code: string
image: string
parent: string
children: string[]
quantity: number
weight: number
noRecalculatePrice: boolean
price: {
vat: {
rate: number
}
created_time: string
discounts?: { id: number; discounted_amount: number }[]
// TODO: add missing fields
total?: {
ati: number
}
unit: {
et: number
ati: number
vat?: number
}
special: {
et: number
ati: number
vat?: number
}
}
atts: any[]
typeDisplay?: string
}
export type AquilacmsAddress = {
firstname: string
lastname: string
companyName: string
phone: string
phone_mobile: string
line1: string
line2: string
zipcode: string
city: string
isoCountryCode: string
country: string
complementaryInfo: string
civility: AquilacmsUserCivility
}
export type AquilacmsCartPromo = {
promoId: string
promoCodeId: string
discountATI: number
discountET: number
name: string
description: string
code: string
gifts: AquilacmsItem[]
productsId: {
productId: string
discountATI: number
discountET: number
basePriceET: number
basePriceATI: number
}[]
}
export type AquilacmsCartCustomer = {
id: string
email: string
phone: string
}
export type AquilacmsCartDiscount = {
code?: string
type?: AquilacmsCartDiscountType
value?: number
description?: string
minimumATI?: number
onAllSite?: boolean
openDate?: string
closeDate?: string
priceATI: number
}
export type AquilacmsCart = {
_id: string
updated: string
paidTax: boolean
status: AquilacmsCartStatus
promos?: AquilacmsCartPromo[]
customer?: AquilacmsCartCustomer
addresses?: {
delivery: AquilacmsAddress
billing: AquilacmsAddress
}
comment?: string
items: AquilacmsItem[]
discount?: AquilacmsCartDiscount[]
delivery?: {
method?: string
value: {
ati: number
et: number
vat: number
}
freePriceLimit?: number
code?: string
name?: string
url?: string
date?: string
dateDelivery?: {
delayDelivery?: number
unitDelivery?: string
delayPreparation?: number
unitPreparation?: string
}
}
priceSubTotal: {
et: number
ati: number
}
priceTotal: {
et: number
ati: number
}
orderReceipt?: {
method: AquilacmsCartOrderReceiptMethod
date?: string
}
createdAt: string
updatedAt: string
}
export type AquilacmsProductAttribute = {
id: string
code: string
values: string[]
value: string
param: string
type: string
position: number
visible: boolean
name: string
}
export type AquilacmsProductImage = {
url: string
name: string
title: string
alt: string
position: number
modificationDate: string
default: boolean
extension: string
}
export type AquilacmsProductPicto = {
code: string
image: string
title: string
location: string
pictoId: string
}
export type AquilacmsProductReviewsQuestion = {
translation: AquilacmsTranslation
idQuestion: string
average: number
}
export type AquilacmsProductReviewsDataQuestion = {
question: string
idQuestion: string
rate: number
}
export type AquilacmsProductReviewsData = {
id_review: string
name: string
id_client: string
ip_client: string
review_date: string
review: string
lang: string
rate: number
order_ref: string
title: string
visible: boolean
verify: boolean
questions: AquilacmsProductReviewsDataQuestion[]
stats: {
views: number
}
}
export type AquilacmsProduct = {
_id: string
code: string
trademark: number
supplier_ref: string
supplier_code: supplierCode
active: boolean
_visible: boolean
universe: string
family: string
subfamily: string
component_template: string
weight: number
price: {
purchase: number
tax: number
et: { normal: number; special: number }
ati: { normal: number; special: number }
priceSort: {
et: number
ati: number
}
}
presentInLastImport: boolean
specific: {
custom_text1: string
custom_text2: string
custom_text3: string
custom_supplier_code: string
custom_traitement: string
custom_code_fabrication: string
}
associated_prds: string[]
set_attributes: string
attributes: AquilacmsProductAttribute[]
images: AquilacmsProductImage[]
code_ean: string
is_new: boolean
translation: AquilacmsTranslation
pictos: AquilacmsProductPicto[]
reviews: {
average: number
reviews_nb: number
questions: AquilacmsProductReviewsQuestion[]
datas: AquilacmsProductReviewsData[]
}
createdAt: string
updatedAt: string
slug: {
[index: string]: string
}
name: string
description1?: {
title: string
text: string
}
description2?: {
title: string
text: string
}
canonical: string
}
export type AquilacmsUserAttribute = {
id: string
code: string
values: string
visible: boolean
param: string
type: string
translation: AquilacmsTranslation
position: number
}
export type AquilacmsUser = {
_id: string
email: string
password: string
code: string
civility: AquilacmsUserCivility
firstname: string
lastname: string
fullname: string
phone: string
phone_mobile: string
company: {
name: string
siret: string
intracom: string
address: string
postal_code: string
town: string
country: string
contact: {
first_name: string
last_name: string
email: string
phone: string
}
}
status: string
delivery_address: number
billing_address: number
addresses: AquilacmsAddress[]
isAdmin: boolean
price: string
taxDisplay: boolean
isActive: boolean
isActiveAccount: boolean
activateAccountToken: string
resetPassToken: string
birthDate: string
accessList: string[]
type: string
preferredLanguage: string
set_attributes: string
attributes: AquilacmsUserAttribute[]
createdAt: string
updatedAt: string
}
export type Cart = Core.Cart & {
@ -54,3 +391,46 @@ export type UpdateCartItemHandlerBody = Core.UpdateCartItemHandlerBody<CartItemB
export type RemoveCartItemBody = Core.RemoveCartItemBody
export type RemoveCartItemHandlerBody = Core.RemoveCartItemHandlerBody
export type User = {
entityId: string
firstName: string
lastName: string
email: string
company?: string
customerGroupId: string
notes: string
phone?: string
addressCount?: number
attributeCount: number
storeCredit: {
value: number
currencyCode: string
}
}
type AquilacmsPage = {
action: string
_id: string
code: string
slug: {
[index: string]: string
}
name: string
metaDescription: string
pageSlug: string
}
export type AquilacmsStatic = {
_id: string
active: boolean
group: string
type: string
code: string
content: string
metaDesc: string
slug: {
[index: string]: string
}
name: string
}

View File

@ -1,3 +0,0 @@
export { default as useAddItem } from './use-add-item'
export { default as useWishlist } from './use-wishlist'
export { default as useRemoveItem } from './use-remove-item'

View File

@ -1,37 +0,0 @@
import { useCallback } from 'react'
import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useAddItem, { UseAddItem } from '@commerce/wishlist/use-add-item'
import type { ItemBody, AddItemBody } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
import useWishlist from './use-wishlist'
export default useAddItem as UseAddItem<typeof handler>
export const handler: MutationHook<any, {}, ItemBody, AddItemBody> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'POST',
},
useHook: ({ fetch }) => () => {
const { data: customer } = useCustomer()
const { revalidate } = useWishlist()
return useCallback(
async function addItem(item) {
if (!customer) {
// A signed customer is required in order to have a wishlist
throw new CommerceError({
message: 'Signed customer not found',
})
}
// TODO: add validations before doing the fetch
const data = await fetch({ input: { item } })
await revalidate()
return data
},
[fetch, revalidate, customer]
)
},
}

View File

@ -1,44 +0,0 @@
import { useCallback } from 'react'
import type { MutationHook } from '@commerce/utils/types'
import { CommerceError } from '@commerce/utils/errors'
import useRemoveItem, {
RemoveItemInput,
UseRemoveItem,
} from '@commerce/wishlist/use-remove-item'
import type { RemoveItemBody, Wishlist } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
import useWishlist, { UseWishlistInput } from './use-wishlist'
export default useRemoveItem as UseRemoveItem<typeof handler>
export const handler: MutationHook<
Wishlist | null,
{ wishlist?: UseWishlistInput },
RemoveItemInput,
RemoveItemBody
> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'DELETE',
},
useHook: ({ fetch }) => ({ wishlist } = {}) => {
const { data: customer } = useCustomer()
const { revalidate } = useWishlist(wishlist)
return useCallback(
async function removeItem(input) {
if (!customer) {
// A signed customer is required in order to have a wishlist
throw new CommerceError({
message: 'Signed customer not found',
})
}
const data = await fetch({ input: { itemId: String(input.id) } })
await revalidate()
return data
},
[fetch, revalidate, customer]
)
},
}

View File

@ -1,60 +0,0 @@
import { useMemo } from 'react'
import { SWRHook } from '@commerce/utils/types'
import useWishlist, { UseWishlist } from '@commerce/wishlist/use-wishlist'
import type { Wishlist } from '../api/wishlist'
import useCustomer from '../customer/use-customer'
export type UseWishlistInput = { includeProducts?: boolean }
export default useWishlist as UseWishlist<typeof handler>
export const handler: SWRHook<
Wishlist | null,
UseWishlistInput,
{ customerId?: number } & UseWishlistInput,
{ isEmpty?: boolean }
> = {
fetchOptions: {
url: '/api/bigcommerce/wishlist',
method: 'GET',
},
async fetcher({ input: { customerId, includeProducts }, options, fetch }) {
if (!customerId) return null
// Use a dummy base as we only care about the relative path
const url = new URL(options.url!, 'http://a')
if (includeProducts) url.searchParams.set('products', '1')
return fetch({
url: url.pathname + url.search,
method: options.method,
})
},
useHook: ({ useData }) => (input) => {
const { data: customer } = useCustomer()
const response = useData({
input: [
['customerId', customer?.entityId],
['includeProducts', input?.includeProducts],
],
swrOptions: {
revalidateOnFocus: false,
...input?.swrOptions,
},
})
return useMemo(
() =>
Object.create(response, {
isEmpty: {
get() {
return (response.data?.items?.length || 0) <= 0
},
enumerable: true,
},
}),
[response]
)
},
}

View File

@ -172,7 +172,7 @@ export interface Product extends Entity {
sku?: string
}
interface ProductOption extends Entity {
export interface ProductOption extends Entity {
displayName: string
values: ProductOptionValues[]
}

View File

@ -34,7 +34,7 @@ module.exports = (nextConfig = {}) => {
config.env = config.env || {}
Object.entries(config.commerce.features).forEach(([k, v]) => {
if (v) config.env[`COMMERCE_${k.toUpperCase()}_ENABLED`] = true
if (v) config.env[`COMMERCE_${k.toUpperCase()}_ENABLED`] = v
})
return config

View File

@ -12,18 +12,18 @@ const isAquilacms = provider === 'aquilacms'
module.exports = withCommerceConfig({
commerce,
i18n: {
locales: ['en-US', 'es'],
locales: ['en-US'],
defaultLocale: 'en-US',
},
rewrites() {
return [
(isBC || isShopify) && {
(isBC || isShopify || isAquilacms) && {
source: '/checkout',
destination: '/api/bigcommerce/checkout',
},
// The logout is also an action so this route is not required, but it's also another way
// you can allow a logout!
isBC && {
(isBC || isAquilacms) && {
source: '/logout',
destination: '/api/bigcommerce/customers/logout?redirect_to=/',
},

View File

@ -2,7 +2,10 @@
"name": "nextjs-commerce",
"version": "1.0.0",
"scripts": {
"dev": "next dev",
"clean": "rm -rf .next",
"predev": "npm run clean",
"dev": "cross-env NODE_OPTIONS='--inspect' next dev",
"prebuild": "npm run clean",
"build": "next build",
"start": "next start",
"analyze": "BUNDLE_ANALYZE=both yarn build",
@ -27,6 +30,7 @@
"dot-object": "^2.1.4",
"email-validator": "^2.0.4",
"immutability-helper": "^3.1.1",
"joi": "^17.4.0",
"js-cookie": "^2.2.1",
"keen-slider": "^5.2.4",
"lodash.debounce": "^4.0.8",
@ -63,6 +67,7 @@
"@types/node": "^14.14.16",
"@types/react": "^17.0.0",
"@types/shopify-buy": "^2.10.5",
"cross-env": "^7.0.3",
"deepmerge": "^4.2.2",
"graphql": "^15.4.0",
"husky": "^4.3.8",

View File

@ -1,5 +1,6 @@
import type {
GetStaticPathsContext,
GetStaticPathsResult,
GetStaticPropsContext,
InferGetStaticPropsType,
} from 'next'
@ -40,7 +41,9 @@ export async function getStaticProps({
}
}
export async function getStaticPaths({ locales }: GetStaticPathsContext) {
export async function getStaticPaths({
locales,
}: GetStaticPathsContext): Promise<GetStaticPathsResult> {
const { pages } = await getAllPages()
const [invalidPaths, log] = missingLocaleInPages()
const paths = pages
@ -53,7 +56,6 @@ export async function getStaticPaths({ locales }: GetStaticPathsContext) {
invalidPaths.push(url)
})
log()
return {
paths,
// Fallback shouldn't be enabled here or otherwise this route

View File

@ -1,3 +1,4 @@
import wishlistApi from '@framework/api/wishlist'
export {}
// import wishlistApi from '@framework/api/wishlist'
export default wishlistApi()
// export default wishlistApi()

View File

@ -144,7 +144,7 @@ export default function Cart() {
</li>
<li className="flex justify-between py-1">
<span>Estimated Shipping</span>
<span className="font-bold tracking-wide">FREE</span>
<span>Calculated at checkout</span>
</li>
</ul>
<div className="flex justify-between border-t border-accents-2 py-3 font-bold mb-10">

View File

@ -6,7 +6,7 @@ import { defaultPageProps } from '@lib/defaults'
import { getConfig } from '@framework/api'
import { useCustomer } from '@framework/customer'
import { WishlistCard } from '@components/wishlist'
import useWishlist from '@framework/wishlist/use-wishlist'
// import useWishlist from '@framework/wishlist/use-wishlist'
import getAllPages from '@framework/common/get-all-pages'
export async function getStaticProps({
@ -56,6 +56,7 @@ export default function Wishlist() {
data &&
// @ts-ignore Shopify - Fix this types
data.items?.map((item) => (
// @ts-ignore
<WishlistCard key={item.id} product={item.product! as any} />
))
)}

View File

@ -22,10 +22,17 @@
"@components/*": ["components/*"],
"@commerce": ["framework/commerce"],
"@commerce/*": ["framework/commerce/*"],
"@framework": ["framework/bigcommerce"],
"@framework/*": ["framework/bigcommerce/*"]
"@framework": ["framework/aquilacms"],
"@framework/*": ["framework/aquilacms/*"]
}
},
"include": ["next-env.d.ts", "**/*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"],
"exclude": ["node_modules"]
"exclude": [
"node_modules/*",
"components/wishlist",
"components/wishlist/WishlistButton",
"components/wishlist/WishlistCard",
"pages/api/bigcommerce/wishlist",
"pages/wishlist"
]
}

1743
yarn.lock

File diff suppressed because it is too large Load Diff