fix: Customer registration (#8896)

* fix: Customer registration

* update test

* one mroe test

* chore: add transformation
This commit is contained in:
Oli Juhl
2024-09-01 11:41:39 +02:00
committed by GitHub
parent 99461e24ab
commit cbb0a6adc7
7 changed files with 269 additions and 10 deletions
@@ -0,0 +1,45 @@
import { MedusaError, ModuleRegistrationName } from "@medusajs/utils"
import { createStep } from "@medusajs/workflows-sdk"
import { CreateCustomerAccountWorkflowInput } from "../workflows"
export const validateCustomerAccountCreationStepId =
"validate-customer-account-creation"
export const validateCustomerAccountCreation = createStep(
validateCustomerAccountCreationStepId,
async (input: CreateCustomerAccountWorkflowInput, { container }) => {
const customerService = container.resolve(ModuleRegistrationName.CUSTOMER)
const { email } = input.customerData
if (!email) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Email is required to create a customer"
)
}
// Check if customer with email already exists
const existingCustomers = await customerService.listCustomers({ email })
if (existingCustomers?.length) {
const hasExistingAccount = existingCustomers.some(
(customer) => customer.has_account
)
if (hasExistingAccount && input.authIdentityId) {
throw new MedusaError(
MedusaError.Types.DUPLICATE_ERROR,
"Customer with this email already has an account"
)
}
if (!hasExistingAccount && !input.authIdentityId) {
throw new MedusaError(
MedusaError.Types.DUPLICATE_ERROR,
"Guest customer with this email already exists"
)
}
}
}
)
@@ -1,16 +1,17 @@
import { CreateCustomerDTO, CustomerDTO } from "@medusajs/types"
import {
createWorkflow,
transform,
WorkflowData,
WorkflowResponse,
} from "@medusajs/workflows-sdk"
import { createCustomersStep } from "../steps"
import { transform } from "@medusajs/workflows-sdk"
import { setAuthAppMetadataStep } from "../../auth"
import { createCustomersStep } from "../steps"
import { validateCustomerAccountCreation } from "../steps/validate-customer-account-creation"
export type CreateCustomerAccountWorkflowInput = {
authIdentityId: string
customersData: CreateCustomerDTO
customerData: CreateCustomerDTO
}
export const createCustomerAccountWorkflowId = "create-customer-account"
@@ -19,8 +20,19 @@ export const createCustomerAccountWorkflowId = "create-customer-account"
*/
export const createCustomerAccountWorkflow = createWorkflow(
createCustomerAccountWorkflowId,
(input: WorkflowData<CreateCustomerAccountWorkflowInput>): WorkflowResponse<CustomerDTO> => {
const customers = createCustomersStep([input.customersData])
(
input: WorkflowData<CreateCustomerAccountWorkflowInput>
): WorkflowResponse<CustomerDTO> => {
validateCustomerAccountCreation(input)
const customerData = transform({ input }, (data) => {
return {
...data.input.customerData,
has_account: !!data.input.authIdentityId,
}
})
const customers = createCustomersStep([customerData])
const customer = transform(
customers,