Skip to content

Commit 55eeda8

Browse files
chore: wip
1 parent 4420cd5 commit 55eeda8

File tree

6 files changed

+87
-63
lines changed

6 files changed

+87
-63
lines changed

storage/framework/core/commerce/src/customers/fetch.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { CustomerTable } from '../types'
1+
import type { CustomersTable } from '../../types'
22
import { db } from '@stacksjs/database'
33

44
export interface FetchCustomersOptions {
@@ -11,7 +11,7 @@ export interface FetchCustomersOptions {
1111
}
1212

1313
export interface PaginatedCustomers {
14-
customers: CustomerTable[]
14+
customers: CustomersTable[]
1515
pagination: {
1616
total: number
1717
currentPage: number
@@ -26,14 +26,14 @@ export interface CustomerStats {
2626
total: number
2727
active: number
2828
inactive: number
29-
topSpenders: Partial<CustomerTable>[]
30-
recentCustomers: Partial<CustomerTable>[]
29+
topSpenders: Partial<CustomersTable>[]
30+
recentCustomers: Partial<CustomersTable>[]
3131
}
3232

3333
/**
3434
* Fetch all customers from the database
3535
*/
36-
export async function fetchAll(): Promise<CustomerTable[]> {
36+
export async function fetchAll(): Promise<CustomersTable[]> {
3737
return await db
3838
.selectFrom('customers')
3939
.selectAll()
@@ -113,7 +113,7 @@ export async function fetchPaginated(options: FetchCustomersOptions = {}): Promi
113113
/**
114114
* Fetch a customer by ID
115115
*/
116-
export async function fetchById(id: number): Promise<CustomerTable | undefined> {
116+
export async function fetchById(id: number): Promise<CustomersTable | undefined> {
117117
return await db
118118
.selectFrom('customers')
119119
.where('id', '=', id)
Lines changed: 11 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
import type { CustomerRequestType } from '@stacksjs/orm'
12
import type { CustomersTable } from '../../../../orm/src/models/Customer'
2-
import type { CreateCustomerInput } from '../../types'
33
import { db } from '@stacksjs/database'
44

55
/**
@@ -8,18 +8,18 @@ import { db } from '@stacksjs/database'
88
* @param data The customer data to store
99
* @returns The newly created customer record
1010
*/
11-
export async function store(data: CreateCustomerInput): Promise<CustomersTable | undefined> {
11+
export async function store(request: CustomerRequestType): Promise<CustomersTable | undefined> {
1212
// Set default values if not provided
1313
const customerData = {
14-
name: data.name,
15-
email: data.email,
16-
phone: data.phone,
17-
orders: data.orders || 0,
18-
totalSpent: data.total_spent || 0,
19-
lastOrder: data.last_order || new Date().toISOString().split('T')[0],
20-
status: data.status || 'Active',
21-
avatar: data.avatar || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
22-
user_id: data.user_id,
14+
name: request.get('name'),
15+
email: request.get('email'),
16+
phone: request.get('phone'),
17+
orders: Number(request.get('orders')) || 0,
18+
total_spent: Number(request.get('totalSpent')) || 0,
19+
last_order: request.get('lastOrder') || new Date().toISOString().split('T')[0],
20+
status: request.get('status') || 'Active',
21+
avatar: request.get('avatar') || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
22+
user_id: Number(request.get('user_id')),
2323
}
2424

2525
try {
@@ -57,45 +57,3 @@ export async function store(data: CreateCustomerInput): Promise<CustomersTable |
5757
throw error
5858
}
5959
}
60-
61-
/**
62-
* Create multiple customers at once
63-
*
64-
* @param customers Array of customer data to store
65-
* @returns Number of customers created
66-
*/
67-
export async function bulkStore(customers: CreateCustomerInput[]): Promise<number> {
68-
if (!customers.length)
69-
return 0
70-
71-
try {
72-
// Prepare customer data with defaults
73-
const customersData = customers.map(data => ({
74-
name: data.name,
75-
email: data.email,
76-
phone: data.phone,
77-
orders: data.orders || 0,
78-
totalSpent: data.total_spent || 0,
79-
lastOrder: data.last_order || new Date().toISOString().split('T')[0],
80-
status: data.status || 'Active',
81-
avatar: data.avatar || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80',
82-
user_id: data.user_id,
83-
}))
84-
85-
// Insert all customers
86-
const result = await db
87-
.insertInto('customers')
88-
.values(customersData)
89-
.execute()
90-
91-
// Return the number of affected rows
92-
return result.length || 0
93-
}
94-
catch (error) {
95-
if (error instanceof Error) {
96-
throw new TypeError(`Failed to create customers in bulk: ${error.message}`)
97-
}
98-
99-
throw error
100-
}
101-
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import type { CustomerRequestType } from '@stacksjs/orm'
2+
import type {
3+
CustomerType,
4+
CustomerUpdate,
5+
} from '../../types'
6+
import { db } from '@stacksjs/database'
7+
8+
/**
9+
* Update a customer by ID
10+
*
11+
* @param id The ID of the customer to update
12+
* @param request The updated customer data
13+
* @returns The updated customer record
14+
*/
15+
export async function update(id: number, request: CustomerRequestType): Promise<CustomerType | undefined> {
16+
try {
17+
// Create the update data object by picking only defined properties from the request
18+
const updateData: CustomerUpdate = Object.entries(request)
19+
.filter(([_, value]) => value !== undefined)
20+
.reduce((obj, [key, value]) => {
21+
obj[key] = value
22+
return obj
23+
}, {} as CustomerUpdate)
24+
25+
// Skip update if no fields are provided
26+
if (Object.keys(updateData).length === 0) {
27+
// Just return the current customer
28+
return await db
29+
.selectFrom('customers')
30+
.where('id', '=', id)
31+
.selectAll()
32+
.executeTakeFirst()
33+
}
34+
35+
// Include updated_at timestamp
36+
updateData.updated_at = new Date()
37+
38+
// Update the customer record
39+
await db
40+
.updateTable('customers')
41+
.set(updateData)
42+
.where('id', '=', id)
43+
.execute()
44+
45+
// Retrieve the updated customer
46+
const updatedCustomer = await db
47+
.selectFrom('customers')
48+
.where('id', '=', id)
49+
.selectAll()
50+
.executeTakeFirst()
51+
52+
return updatedCustomer
53+
}
54+
catch (error) {
55+
// Handle specific errors
56+
if (error instanceof Error) {
57+
// Check for unique constraint violation on email
58+
if (error.message.includes('Duplicate entry') && error.message.includes('email')) {
59+
throw new Error('A customer with this email already exists')
60+
}
61+
62+
// Re-throw the error with a more user-friendly message
63+
throw new Error(`Failed to update customer: ${error.message}`)
64+
}
65+
66+
throw error
67+
}
68+
}

storage/framework/orm/src/models/Order.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import type { Insertable, RawBuilder, Selectable, Updateable } from '@stacksjs/database'
22
import type { Operator } from '@stacksjs/orm'
33
import type { CouponModel } from './Coupon'
4-
import type { OrderModel } from './Order'
54
import type { UserModel } from './User'
65
import { randomUUIDv7 } from 'bun'
76
import { cache } from '@stacksjs/cache'
@@ -14,7 +13,6 @@ import { DB, SubqueryBuilder } from '@stacksjs/orm'
1413

1514
import Coupon from './Coupon'
1615

17-
import Order from './Order'
1816

1917
import User from './User'
2018

storage/framework/server-auto-imports.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,4 @@
244244
"transactionRequest": true,
245245
"userRequest": true
246246
}
247-
}
247+
}

storage/framework/types/server-auto-imports.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,4 @@ declare global {
244244
const teamRequest: typeof import('./../requests')['teamRequest']
245245
const transactionRequest: typeof import('./../requests')['transactionRequest']
246246
const userRequest: typeof import('./../requests')['userRequest']
247-
}
247+
}

0 commit comments

Comments
 (0)