This commit is contained in:
2025-10-02 08:18:37 +00:00
parent ea54638227
commit f81250a7c1
225 changed files with 76 additions and 23002 deletions

View File

@@ -1,46 +0,0 @@
const { getCart, getRedirectUrl } = require("../lib/bigcommerceRestAPI")
const { bigcommerceStoreHash, bigcommerceBaseURL, bigCommerceCliendId, bigCommerceClientSecret } = require("../config")
const { getCustomerById, getLoginUrl } = require("../lib/bigcommerceRestAPI")
const { withAccount } = require("../lib/utils")
const { mapRestApiCartToGraphQL } = require("./helper")
;(function () {
if (context.user.auth()) return {}
const checkout = context.request().query("checkout")
const loggedInCheckout = context.request().query("loggedInCheckout")
if (checkout) {
if (loggedInCheckout) {
withAccount((loginClaims) => {
const cartId = context.request().param("id")
const cart = getCart(cartId)
const { checkoutURL } = getRedirectUrl(cartId)
const loginUrl = getLoginUrl(
loginClaims.bigCommerceId,
bigcommerceStoreHash,
bigcommerceBaseURL,
bigCommerceCliendId,
bigCommerceClientSecret,
checkoutURL.split(bigcommerceBaseURL).pop()
)
throw {
status: 200,
data: cart && {
cart: mapRestApiCartToGraphQL(cart),
checkoutURL: loginUrl,
},
}
})
}
}
const cartId = context.request().param("id")
const cart = getCart(cartId)
const { checkoutURL, embeddedCheckoutURL } = getRedirectUrl(cartId)
throw {
status: 200,
data: cart && {
cart: mapRestApiCartToGraphQL(cart),
checkoutURL: checkoutURL,
embeddedCheckoutURL: embeddedCheckoutURL,
},
}
})()

View File

@@ -1,53 +0,0 @@
/**
*
* @param {RestApiCart} cart
* @returns {BigCommerceCart}
*/
function mapRestApiCartToGraphQL(cart) {
return {
entityId: cart.id,
currencyCode: cart.currency.code,
isTaxIncluded: cart.tax_included,
baseAmount: { value: cart.base_amount, currencyCode: cart.currency.code },
discountedAmount: { value: cart.discount_amount, currencyCode: cart.currency.code },
amount: { value: cart.cart_amount, currencyCode: cart.currency.code },
discounts: cart.discounts.map((d) => ({
entityId: d.id,
discountedAmount: { value: d.discounted_amount, currencyCode: cart.currency.code },
})),
lineItems: {
physicalItems: cart.line_items.physical_items.map((item) => ({
entityId: item.id,
parentEntityId: cart.parent_id,
productEntityId: item.product_id,
variantEntityId: item.variant_id,
sku: item.sku,
name: item.name,
url: item.url,
imageUrl: item.image_url,
brand: "BKDF", // REST API does not provide brand directly
quantity: item.quantity,
isTaxable: item.is_taxable,
listPrice: { value: item.list_price, currencyCode: cart.currency.code },
extendedListPrice: { value: item.extended_list_price, currencyCode: cart.currency.code },
selectedOptions: item?.options?.map((option) => ({
// Map each option to the GraphQL format
// Assuming a simplified structure here for the example
})),
isShippingRequired: true, // Example assumption
})),
digitalItems: [],
customItems: [],
giftCertificates: [],
totalQuantity: cart.line_items.physical_items.reduce((total, item) => total + item.quantity, 0),
},
createdAt: { utc: new Date(cart.created_time) },
updatedAt: { utc: new Date(cart.updated_time) },
locale: cart.locale,
}
}
module.exports = {
mapRestApiCartToGraphQL,
}

View File

@@ -1,25 +0,0 @@
const { addCartItem, updateCartItem, deleteCartItem, getCart } = require("../lib/bigcommerceRestAPI")
const { postAddToCart } = require("../lib/facebookRestAPI")
;(function () {
const operation = context?.data?.operation
if (operation == "add") {
addCartItem(context?.data?.cartId, context?.data?.lineItems)
try {
postAddToCart()
} catch (e) {}
} else if (operation == "update") {
updateCartItem(context?.data?.cartId, context?.data?.lineItem, context?.data?.entityId)
try {
postAddToCart()
} catch (e) {}
} else if (operation == "delete") {
deleteCartItem(context?.data?.cartId, context?.data?.entityId)
}
throw {
status: 200,
message: "success",
}
})()

View File

@@ -1,55 +0,0 @@
const { getCustomerAddressById, getCustomerAddresses, getCustomerById } = require("../lib/bigcommerceRestAPI")
const { withAccount } = require("../lib/utils")
;(function () {
console.log("wtf")
if (context.user.auth()) return
const request = context.request()
const queryUsername = request.query("username")
if (queryUsername) {
const user = context.db.find("bigCommerceCustomer", {
filter: { username: queryUsername },
})[0]
if (!user) {
throw { status: 404, error: "customer not found" }
}
throw {
data: {
id: user.id,
username: user.username,
socialMediaAccounts: user.socialMediaAccounts,
personalRecords: user.personalRecords,
},
status: 200,
}
}
const foreign = request.query("foreign")
if (foreign) {
const id = request.param("id")
const user = context.db.find("bigCommerceCustomer", {
filter: { _id: id },
})[0]
if (!user) {
throw { status: 404, error: "customer not found" }
}
throw {
data: {
id: user.id,
username: user.username,
socialMediaAccounts: user.socialMediaAccounts,
personalRecords: user.personalRecords,
},
status: 200,
}
}
withAccount((loginClaims) => {
const queryAddressId = request.query("address")
const queryAddresses = request.query("addresses")
if (queryAddressId) {
throw { data: getCustomerAddressById(loginClaims.bigCommerceId, Number(queryAddressId)), status: 200 }
} else if (queryAddresses) {
throw { data: getCustomerAddresses(loginClaims.bigCommerceId), status: 200 }
} else throw { data: getCustomerById(loginClaims.bigCommerceId), status: 200 }
})
throw { status: 401, error: "unauthorized", log: false }
})()

View File

@@ -1,250 +0,0 @@
const {
updateCustomer,
updateCustomerAddressById,
deleteCustomerAddressById,
addCustomerAddress,
validateCredentials,
getCustomerById,
} = require("../lib/bigcommerceRestAPI")
const { withAccount } = require("../lib/utils")
const { getJwt } = require("../lib/utils")
const emailRegex =
/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/
;(function () {
if (context.user.auth()) return
let data = context.data
const r = context.request()
const customerId = r.param("id")
const backendAuth = context.user.auth()
let returnCustomer = undefined
if (!backendAuth) {
// require authorization header with jwt
const token = getJwt(context)
/** @type {JWTPwResetClaims} */ // @ts-ignore
const pwResetClaims = token.claims
/** @type {Customer} */ // @ts-ignore
const customer = context.db.find("bigCommerceCustomer", {
filter: { _id: pwResetClaims.tibiId },
})[0]
if (!customer) {
throw {
status: 404,
error: "customer not found",
log: false,
}
}
if (data.operation === "resetPassword") {
if (pwResetClaims && pwResetClaims.tibiId && pwResetClaims.check) {
// is password reset token since it has .check
if (pwResetClaims.tibiId != customerId)
throw {
status: 403,
error: "token not valid for this id",
log: false,
}
if (pwResetClaims.check != customer.currentToken)
throw {
status: 403,
error: "password reset token expired",
log: false,
}
updateCustomer({
authentication: {
force_password_reset: false,
new_password: data.password,
},
id: Number(customer.bigCommerceId),
})
throw {
status: 200,
log: false,
}
} else {
throw {
status: 403,
error: "invalid token",
log: false,
}
}
}
withAccount((loginClaims) => {
/** @type {BigCommerceCustomer} */
const customer = data.customer
if (customer) customer.id = Number(loginClaims.bigCommerceId)
if (data.operation === "updateCustomer") {
customer.email = loginClaims.email
const index = customer.form_fields.findIndex((f) => f.name === "username")
const internalCustomer = context.db.find("bigCommerceCustomer", {
filter: { email: customer.email },
})[0]
if (index >= 0) customer.form_fields[index].value = internalCustomer.username
const response = updateCustomer(customer)
throw {
status: 200,
data: response,
message: "customer updated",
log: false,
}
} else if (data.operation == "updateInternalCustomer") {
const customer = data.customer
returnCustomer = customer
} else if (data.operation === "updateCustomerAddress") {
/** @type {BigCommerceAddress} */
const address = data.address
address.customer_id = Number(loginClaims.bigCommerceId)
const response = updateCustomerAddressById(address)
throw {
status: 200,
message: "customer addresses updated",
data: response,
log: false,
}
} else if (data.operation === "deleteCustomerAddress") {
deleteCustomerAddressById(Number(loginClaims.bigCommerceId), data.addressId)
throw {
status: 200,
message: "customer address deleted",
data: {
success: true,
},
log: false,
}
} else if (data.operation === "addCustomerAddress") {
/** @type {BigCommerceAddress} */
const address = data.address
address.customer_id = Number(loginClaims.bigCommerceId)
delete address.id
const response = addCustomerAddress(address)
throw {
status: 200,
message: "customer addresses updated",
data: response,
log: false,
}
} else if (data.operation === "changePassword") {
const res = validateCredentials(loginClaims.email, data.currentPassword)
if (!res.is_valid) {
throw {
status: 403,
error: "current password incorrect",
log: false,
}
}
const resPw = updateCustomer({
authentication: {
force_password_reset: false,
new_password: data.newPassword,
},
id: Number(loginClaims.bigCommerceId),
})
throw {
status: 200,
message: "password reset successful",
log: false,
}
} else if (data.operation === "updateEmail") {
const resValidation = validateCredentials(loginClaims.email, data.password)
if (!resValidation.is_valid) {
throw {
status: 403,
error: "password incorrect",
log: false,
}
}
if (!data.email)
throw {
status: 400,
error: "email is required",
log: false,
}
data.email = data.email.toLowerCase()
const customers = context.db.find("bigCommerceCustomer", {
filter: { email: data.email },
})
if (customers.length > 0)
throw {
status: 409,
error: "email already in use",
log: false,
}
if (emailRegex.test(data.email) === false) {
throw {
status: 400,
error: "invalid email",
log: false,
}
}
const res = updateCustomer({ id: Number(loginClaims.bigCommerceId), email: data.email })
context.db.update("bigCommerceCustomer", loginClaims.tibiId, { email: data.email })
throw {
status: 200,
message: "customer updated",
data: res,
log: false,
}
} else if (data.operation === "updateUsername") {
const resValidation = validateCredentials(loginClaims.email, data.password)
if (!resValidation.is_valid) {
throw {
status: 403,
error: "password incorrect",
log: false,
}
}
/**@type {string} */
let username = data.username
if (!username)
throw {
status: 400,
error: "username is required",
log: false,
}
username = username.toLowerCase()
const userWithUsername = context.db.find("bigCommerceCustomer", {
filter: { username: username },
})[0]
if (userWithUsername)
throw {
status: 409,
message: "username already in use",
}
const internalCustomer = context.db.find("bigCommerceCustomer", {
filter: { email: loginClaims.email },
})[0]
internalCustomer.username = username
if (internalCustomer) {
context.db.update("bigCommerceCustomer", internalCustomer.id, internalCustomer)
}
//update bigcommerce customer too : get it and then update it with username swapped
const bCCustomer = getCustomerById(loginClaims.bigCommerceId)
if (!bCCustomer.form_fields) bCCustomer.form_fields = []
const usernameIndex = bCCustomer.form_fields.findIndex((f) => f.name === "username")
if (usernameIndex >= 0) bCCustomer.form_fields[usernameIndex].value = username
else bCCustomer.form_fields = [...bCCustomer.form_fields, { name: "username", value: username }]
updateCustomer(bCCustomer)
throw {
status: 200,
message: "customer updated",
data: internalCustomer,
log: false,
}
}
})
}
if (returnCustomer) {
return {
data: returnCustomer,
}
}
throw { status: 401, error: "unauthorized", log: false }
})()

View File

@@ -1,56 +0,0 @@
const { getOrderById, getOrdersForCustomer, createInternalOrderObject } = require("../lib/bigcommerceRestAPI")
const { withAccount } = require("../lib/utils")
;(function () {
if (context.user.auth()) return {}
withAccount((login) => {
const orderId = context.request().param("id")
if (orderId) {
/** @type {Order} */
// @ts-ignore
const internalOrder = context.db.find("bigCommerceOrder", {
filter: { _id: orderId },
})[0]
if (internalOrder.customerTibiId !== login.tibiId) {
if (String(internalOrder?.customerBigCommerceId) !== String(login?.bigCommerceId)) {
throw {
message: "You don't have permission to access this order",
code: 403,
}
} else {
context.db.update("bigCommerceOrder", internalOrder.id, {
customerTibiId: login.tibiId,
})
}
}
const order = getOrderById(internalOrder.bigCommerceId)
order.tibiId = internalOrder.id
order.status = internalOrder.status
order.shipments = internalOrder.shipments
order.statusSetAt = internalOrder.statusSetAt
throw {
data: order,
status: 200,
}
} else {
const orders = getOrdersForCustomer(login.bigCommerceId)
orders.forEach((order) => {
let internalOrder = context.db.find("bigCommerceOrder", {
filter: { bigCommerceId: order.id },
})[0]
if (!internalOrder && order.id) {
const internalOrderReference = createInternalOrderObject(order.id)
internalOrder = context.db.create("bigCommerceOrder", internalOrderReference)
} else if (!internalOrder) return
order.tibiId = internalOrder?.id
order.status = internalOrder?.status
order.shipments = internalOrder?.shipments
order.statusSetAt = internalOrder?.statusSetAt
})
throw {
data: orders,
status: 200,
}
}
})
})()

View File

@@ -1,5 +0,0 @@
import { withAccount } from "../lib/utils"
;(function () {
if (context.user.auth()) return {}
withAccount((login) => {})
})

View File

@@ -1,47 +0,0 @@
const { withAccount } = require("../lib/utils")
;(function () {
withAccount((login) => {
const id = context.request().param("id")
if (!id) {
throw {
message: "id is required",
code: 400,
}
}
const existingReturnRequest = context.db.find("orderReturnRequest", {
filter: {
_id: id,
},
})[0]
if (!existingReturnRequest)
throw {
message: "Return request not found",
code: 404,
}
const order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: Number(existingReturnRequest.bigCommerceId),
},
})[0]
if (!order)
throw {
message: "Order not found",
code: 404,
}
if (order.customerBigCommerceId !== login.bigCommerceId)
throw {
message: "You don't have permission to access this order",
code: 403,
}
if (
existingReturnRequest.status !== "pending" &&
existingReturnRequest.status !== "approved" &&
!!existingReturnRequest.status
)
throw {
message: "Return request is not pending or approved",
code: 400,
}
})
})()

View File

@@ -1,33 +0,0 @@
const { serverBaseURL, logoPath, operatorEmail, noReplyEmail, contactEmail } = require("../config")
const { frontendBase } = require("../config-client")
const { withAccount } = require("../lib/utils")
;(function () {
if (context.user.auth()) return
withAccount((login) => {
const store = {
logo: `${serverBaseURL}${logoPath}`,
frontendBase,
}
const html = context.tpl.execute(context.fs.readFile("templates/orderReturnRequestRevoked.html"), {
store,
})
context.smtp.sendMail({
to: contactEmail,
from: noReplyEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "New Order Return Request Cancellation",
plain: `Die Bestellung von ${login.email} soll doch nicht zurückgegeben werden.`,
})
context.smtp.sendMail({
to: login.email,
from: operatorEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "Widerruf deiner Bestellung abgebrochen",
html,
})
})
})()

View File

@@ -1,41 +0,0 @@
const { withAccount } = require("../lib/utils")
;(function () {
const queryParam = context.request().query("orderId")
if (!queryParam) {
if (context.user.auth()) return
throw {
message: "orderId is required",
code: 400,
}
}
withAccount((login) => {
const order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: Number(queryParam),
},
})[0]
if (!order) {
throw {
message: "Order not found",
code: 404,
}
}
if (order.customerBigCommerceId !== login.bigCommerceId) {
console.log(
"order.customerBigCommerceId",
order.customerBigCommerceId,
"login.bigCommerceId",
login.bigCommerceId
)
throw {
message: "You don't have permission to access this order",
code: 403,
}
}
context.filter = {
bigCommerceId: order.bigCommerceId,
}
})
return context
})()

View File

@@ -1,81 +0,0 @@
const { withAccount } = require("../lib/utils")
const { getOrderProductsById } = require("../lib/bigcommerceRestAPI")
;(function () {
if (context.user.auth()) return
withAccount((login) => {
const order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: Number(context.data.bigCommerceId),
},
})[0]
if (!order)
throw {
message: "Order not found",
code: 404,
}
if (order.customerBigCommerceId !== login.bigCommerceId)
throw {
message: "You don't have permission to access this order",
code: 403,
}
const bigcommerceProducts = getOrderProductsById(context.data.bigCommerceId)
const returnRequestProducts = context.data.products
// make sure all ids are also in the orderproducts
returnRequestProducts.forEach((/** @type {OrderReturnRequestProduct} */ returnRequestProduct) => {
const bigcommerceProduct = bigcommerceProducts.find(
(bigcommerceProduct) => Number(bigcommerceProduct.id) === returnRequestProduct.productId
)
if (!bigcommerceProduct)
throw {
message: "Product not found",
code: 404,
}
if (bigcommerceProduct.quantity < returnRequestProduct.quantity)
throw {
message: "Quantity exceeds the available quantity",
code: 400,
}
const existingReturnRequests = context.db.find("orderReturnRequest", {
filter: {
bigCommerceId: context.data.bigCommerceId,
$or: [
{
status: "pending",
},
{
status: "approved",
},
{
status: "refunded",
},
],
},
})
returnRequestProduct.baseProductId = bigcommerceProduct.product_id
let totalExistingQuantity = 0
existingReturnRequests.forEach((existingReturnRequest) => {
existingReturnRequest.products.forEach(
(/** @type {OrderReturnRequestProduct} */ existingReturnRequestProduct) => {
if (existingReturnRequestProduct.productId === returnRequestProduct.productId) {
totalExistingQuantity += existingReturnRequestProduct.quantity
}
}
)
})
if (totalExistingQuantity + returnRequestProduct.quantity > bigcommerceProduct.quantity) {
throw {
message: "Quantity exceeds the available quantity",
code: 400,
}
}
})
context.data.products = context.data.products.filter(
(/** @type {OrderReturnRequestProduct} */ p) => p.quantity > 0
)
context.data.status = "pending"
context.data.email = login.email
})
return context
})()

View File

@@ -1,30 +0,0 @@
const { serverBaseURL, logoPath, operatorEmail, noReplyEmail, contactEmail } = require("../config")
const { frontendBase } = require("../config-client")
;(function () {
const store = {
logo: `${serverBaseURL}${logoPath}`,
frontendBase,
}
const html = context.tpl.execute(context.fs.readFile("templates/orderReturnRequestApproval.html"), {
store,
})
context.smtp.sendMail({
to: contactEmail,
from: noReplyEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "New Order Return Request",
plain: `Die Bestellung von ${context.data.email} soll zurückgegeben werden.`,
})
context.smtp.sendMail({
to: context.data.email,
from: operatorEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "Widerruf deiner Bestellung",
html,
})
})()

View File

@@ -1,51 +0,0 @@
const { logoPath, noReplyEmail, operatorEmail, serverBaseURL } = require("../config")
const { frontendBase } = require("../config-client")
const { getOrderById, updateOrderById } = require("../lib/bigcommerceRestAPI")
;(function () {
const oldOrderReturnRequest = context.db.find("orderReturnRequest", {
filter: {
_id: context.data.id,
},
})[0]
if (!oldOrderReturnRequest)
throw {
message: "Order return request not found",
code: 404,
}
if (context.data.status == "approved") {
const bigCommerceOrder = getOrderById(context.data.bigCommerceId)
delete bigCommerceOrder.productObjs
delete bigCommerceOrder.shipping_addressObjs
bigCommerceOrder.status_id = 5
updateOrderById(bigCommerceOrder.id, { status_id: 5 })
}
if (oldOrderReturnRequest.status !== context.data.status) {
const oRR = context.data
const customer = context.db.find("bigCommerceCustomer", {
filter: { email: oRR.email },
})[0]
if (!customer) {
throw {
status: 404,
message: "Customer not found",
}
}
const store = {
logo: `${serverBaseURL}${logoPath}`,
frontendBase,
}
const html = context.tpl.execute(context.fs.readFile("templates/statusUpdateReturnRequest.html"), {
store,
})
context.smtp.sendMail({
to: oRR.email,
from: operatorEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "Stornierung deiner Bestellung",
html,
})
}
})()

View File

@@ -1,35 +0,0 @@
const { withAccount } = require("../lib/utils")
;(function () {
const queryParam = context.request().query("orderId")
if (!queryParam) {
if (context.user.auth()) return
throw {
message: "orderId is required",
code: 400,
}
}
withAccount((login) => {
const order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: Number(queryParam),
},
})[0]
if (!order) {
throw {
message: "Order not found",
code: 404,
}
}
if (order.customerBigCommerceId !== login.bigCommerceId) {
throw {
message: "You don't have permission to access this order",
code: 403,
}
}
context.filter = {
bigCommerceId: order.bigCommerceId,
}
})
return context
})()

View File

@@ -1,45 +0,0 @@
const { withAccount } = require("../lib/utils")
const { getPrintfulOrder, cancelPrintfulOrder } = require("../lib/printfulRestAPI")
;(function () {
withAccount((login) => {
const order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: Number(context.data.bigCommerceId),
},
})[0]
if (!order)
throw {
message: "Order not found",
code: 404,
}
if (order.customerBigCommerceId !== login.bigCommerceId)
throw {
message: "You don't have permission to access this order",
code: 403,
}
const existingRevokeRequests = context.db.find("orderRevokeRequest", {
filter: {
bigCommerceId: context.data.bigCommerceId,
},
})
if (existingRevokeRequests.length > 0)
throw {
message: "Revoke request already exists",
code: 400,
}
if (!!order.status && order.status !== "draft") {
throw {
message: "Order is already in process",
code: 400,
}
}
const printfulOrder = getPrintfulOrder(order.bigCommerceId)
cancelPrintfulOrder(context.data.bigCommerceId)
context.data.status = "pending"
context.data.email = login.email
context.data.printfulId = printfulOrder.id
})
return context
})()

View File

@@ -1,36 +0,0 @@
const { serverBaseURL, logoPath, operatorEmail, noReplyEmail, contactEmail } = require("../config")
const { frontendBase } = require("../config-client")
const { getOrderById, updateOrderById } = require("../lib/bigcommerceRestAPI")
;(function () {
if (context.user.auth()) return
const bigCommerceOrder = getOrderById(context.data.bigCommerceId)
delete bigCommerceOrder.productObjs
delete bigCommerceOrder.shipping_addressObjs
bigCommerceOrder.status_id = 5
updateOrderById(bigCommerceOrder.id, { status_id: 5 })
const store = {
logo: `${serverBaseURL}${logoPath}`,
frontendBase,
}
const html = context.tpl.execute(context.fs.readFile("templates/orderRevokedApproval.html"), {
store,
})
context.smtp.sendMail({
to: contactEmail,
from: noReplyEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "New Order Revoke Request",
plain: `Die Bestellung von ${context.data.email} wurde abgebrochen.`,
})
context.smtp.sendMail({
to: context.data.email,
from: operatorEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "Abbruch deiner Bestellung",
html,
})
})()

View File

@@ -1,43 +0,0 @@
import { logoPath, noReplyEmail, operatorEmail, serverBaseURL } from "../config"
import { frontendBase } from "../config-client"
;(function () {
const oldOrderReturnRequest = context.db.find("orderReturnRequest", {
filter: {
_id: context.data.id,
},
})[0]
if (!oldOrderReturnRequest)
throw {
message: "Order return request not found",
code: 404,
}
if (oldOrderReturnRequest.status !== context.data.status) {
const oRR = context.data
const customer = context.db.find("bigCommerceCustomer", {
filter: { email: oRR.email },
})[0]
if (!customer) {
throw {
status: 404,
message: "Customer not found",
}
}
const store = {
logo: `${serverBaseURL}${logoPath}`,
frontendBase,
}
const html = context.tpl.execute(context.fs.readFile("templates/statusUpdateReturnRequest.html"), {
store,
})
context.smtp.sendMail({
to: oRR.email,
from: operatorEmail,
fromName: "BinKrassDuFass",
replyTo: noReplyEmail,
subject: "Stornierung Ihrer Bestellung",
html,
})
}
})()

View File

@@ -1,23 +0,0 @@
const { attachRatingObjsToProduct } = require("./helper")
;(function () {
if (context.user.auth()) return
const bigCommerceProductId = context.request().query("bigCommerceProductId")
if (bigCommerceProductId) {
/**@type {LocalProduct[]} */
//@ts-ignore
let products = context.db.find("bigCommerceProduct", {
filter: {
bigCommerceId: Number(bigCommerceProductId),
},
})
products = attachRatingObjsToProduct(products)
if (products.length > 0) {
throw {
status: 200,
data: products[0],
}
}
}
return
})()

View File

@@ -1,12 +0,0 @@
const { attachRatingObjsToProduct } = require("./helper")
;(function () {
if (context.user.auth()) return
/**@type {LocalProduct[]} */
//@ts-ignore
let products = context.results()
products = attachRatingObjsToProduct(products)
let hookResponse = {
results: products,
}
return hookResponse
})()

View File

@@ -1,26 +0,0 @@
/**
* @param {LocalProduct[]} products
* @returns {LocalProduct[]}
*/
function attachRatingObjsToProduct(products) {
let productIds = products.map((product) => product.bigCommerceId)
/**@type {ProductRating[]} */
//@ts-ignore
let allRatings = context.db.find("rating", {
filter: {
status: "approved",
bigCommerceProductId: { $in: productIds },
},
})
products.forEach((product, i) => {
let ratings = allRatings.filter((rating) => rating.bigCommerceProductId === product.bigCommerceId).reverse()
products[i].ratings = ratings
})
return products
}
module.exports = {
attachRatingObjsToProduct,
}

View File

@@ -1,36 +0,0 @@
const { getAllProducts, getProductImages } = require("../lib/bigcommerceRestAPI")
const { extractSizingChart } = require("../lib/printfulRestAPI")
;(function () {
const products = getAllProducts()
const productIds = products.map((p) => p.id)
const currentProducts = context.db.find("bigCommerceProduct", { filter: { bigCommerceId: { $in: productIds } } })
const notFoundProductIds = productIds.filter((id) => !currentProducts.some((p) => p.bigCommerceId == id))
const newProducts = products.filter((p) => notFoundProductIds.includes(p.id))
newProducts.forEach((p) => {
const productImage = getProductImages(String(p.id))
context.db.create("bigCommerceProduct", {
forcedWarning: "",
productName: p.name_customer || p.name,
previewImage: productImage?.[0]?.url_thumbnail,
bigCommerceId: p?.id,
sizingChart: null,
})
})
currentProducts.forEach((p) => {
context.db.update("bigCommerceProduct", p.id, {
...p,
productName:
products.find((bp) => bp.id == p.bigCommerceId).name_customer ||
products.find((bp) => bp.id == p.bigCommerceId).name,
bigCommerceSKU: products.find((bp) => bp.id == p.bigCommerceId).sku,
bigCommerceId: products.find((bp) => bp.id == p.bigCommerceId).id,
sizingChart: extractSizingChart(p.printfulProductId, p.id),
})
})
throw {
status: 200,
message: "Products created or updated successfully",
}
})()

View File

@@ -1,13 +0,0 @@
const { extractSizingChart } = require("../lib/printfulRestAPI")
let { clearSSRCache } = require("../lib/utils")
;(function () {
clearSSRCache()
if (context.data.printfulProductId) {
const sizingChart = extractSizingChart(context.data.printfulProductId, context.data.id)
if (sizingChart) {
context.data.sizingChart = sizingChart
return { data: context.data }
}
}
})()

View File

@@ -1,15 +0,0 @@
;(function () {
const ratingId = context.request().param("id")
let rating = context.db.find("rating", {
filter: {
_id: ratingId,
},
})[0]
if (!rating.id)
throw {
status: 400,
error: "No id specified.",
}
// @ts-ignore
context["rating"] = rating
})()

View File

@@ -1,7 +0,0 @@
let { clearSSRCache } = require("../lib/utils")
let { deleteRating } = require("../lib/bigcommerceRestAPI")
;(function () {
clearSSRCache()
// @ts-ignore
deleteRating(context["rating"].bigCommerceProductId, context["rating"].bigcommerceReviewId)
})()

View File

@@ -1,46 +0,0 @@
// @ts-check
const { withAccount } = require("../lib/utils")
;(function () {
/** @type {HookResponse} */
let hookResponse
let request = context.request()
if (context.user.auth()) return
const orderId = Number(request.query("orderId"))
if (orderId) {
withAccount((login) => {
let order = context.db.find("bigCommerceOrder", {
filter: {
bigCommerceId: orderId,
customerBigCommerceId: login.bigCommerceId,
},
})[0]
if (!order) {
throw {
status: 404,
data: {
message: "Order not found",
},
}
}
})
hookResponse = {
filter: {
bigcommerceOrderId: orderId,
},
}
return hookResponse
} else {
hookResponse = {
filter: context.filter,
selector: {
bigCommerceProductId: 1,
rating: 1,
comment: 1,
title: 1,
review_date: 1,
},
}
return hookResponse
}
})()

View File

@@ -1,17 +0,0 @@
const { productInsideOrder } = require("../lib/utils")
;(function () {
if (!context?.user?.auth()?.id) {
if (!context.data) throw { status: 400, error: "No data provided" }
// @ts-ignore
productInsideOrder(context.data)
/** @type {ProductRating[]} */ // @ts-ignore
let ratings = context.db.find("rating", {
filter: {
bigcommerceOrderId: context?.data?.bigcommerceOrderId,
bigCommerceProductId: context?.data?.bigCommerceProductId,
},
})
if (ratings.length) throw { status: 400, error: "Rating already existing" }
}
})()

View File

@@ -1,41 +0,0 @@
const { bigcommerceApiOAuth, serverBaseURL, bigcommerceStoreHash } = require("../config.js")
let { sendOperatorRatingMail, clearSSRCache, statusIsValid } = require("../lib/utils")
;(function () {
const response = context.http.fetch(
`https://api.bigcommerce.com/stores/${bigcommerceStoreHash}/v3/catalog/products/${context?.data?.bigCommerceProductId}/reviews`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Auth-Token": bigcommerceApiOAuth,
},
body: JSON.stringify({
title: context?.data?.title,
comment: context?.data?.comment,
status:
context?.data?.status === "approved"
? "approved"
: context?.data?.status == "pending"
? "pending"
: "disapproved",
rating: context?.data?.rating?.overall,
date_reviewed: context?.data?.review_date,
}),
}
)
if (!statusIsValid(response.status)) {
throw {
status: response.status,
error: response.statusText,
}
}
const bigcommerceRating = response.body.json()
context.db.update("rating", context?.data?.id || "", {
bigcommerceReviewId: String(bigcommerceRating?.data?.id),
})
clearSSRCache()
sendOperatorRatingMail()
})()

View File

@@ -1,5 +0,0 @@
let { validateAndModifyRating } = require("../lib/utils")
;(function () {
// @ts-ignore
return { data: validateAndModifyRating(context.data) }
})()

View File

@@ -1,42 +0,0 @@
let { sendOperatorRatingMail, clearSSRCache, statusIsValid } = require("../lib/utils")
const { bigcommerceApiOAuth, bigcommerceStoreHash } = require("../config.js")
;(function () {
const response = context.http.fetch(
// @ts-ignore
`https://api.bigcommerce.com/stores/${bigcommerceStoreHash}/v3/catalog/products/${context?.data?.bigCommerceProductId}/reviews/${context["oldRating"]?.bigcommerceReviewId}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"X-Auth-Token": bigcommerceApiOAuth,
},
body: JSON.stringify({
title: context?.data?.title,
comment: context?.data?.comment,
status:
context?.data?.status === "approved"
? "approved"
: context?.data?.status == "pending"
? "pending"
: "disapproved",
rating: context?.data?.rating?.overall,
date_reviewed: context?.data?.review_date,
}),
}
)
if (!statusIsValid(response.status)) {
throw {
status: response.status,
error: response.statusText,
}
}
let rating = context.data
// @ts-ignore
let oldRating = context["oldRating"]
// @ts-ignore
if (!oldRating || JSON.stringify(rating) != JSON.stringify(oldRating)) {
sendOperatorRatingMail()
clearSSRCache()
}
})()

View File

@@ -1,16 +0,0 @@
const { productInsideOrder } = require("../lib/utils")
;(function () {
if (!context?.user?.auth()?.id) {
// @ts-ignore
productInsideOrder(context?.data)
}
/** @type {ProductRating} */ // @ts-ignore
let ratingObj = context.db.find("rating", {
filter: {
_id: context?.data?.id,
},
})[0]
// @ts-ignore
context["oldRating"] = ratingObj
})()

View File

@@ -1,5 +0,0 @@
let { validateAndModifyRating } = require("../lib/utils")
;(function () {
// @ts-ignore
return { data: validateAndModifyRating(context.data) }
})()