Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions app/(api)/_datalib/_resolvers/Order.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import Orders from '../_services/Orders';
import { OrderInput, Order, OrderProductInput } from '@datatypes/Order';
import {
Order,
OrderInput,
OrderProductInput,
OrderStatus,
CancellationStatus,
} from '@datatypes/Order';
import { ApolloContext } from '../apolloServer';

const resolvers = {
Expand All @@ -13,14 +19,32 @@ const resolvers = {
orders: (
_: never,
args: {
statuses: string[];
statuses: OrderStatus[];
cancellation_statuses: CancellationStatus[];
search: string;
offset: number;
limit: number;
},
ctx: ApolloContext
) =>
Orders.findMany(args.statuses, args.search, args.offset, args.limit, ctx),
Orders.findMany(
args.statuses,
args.cancellation_statuses,
args.search,
args.offset,
args.limit,
ctx
),
ordersCount: (
_: never,
args: {
statuses: OrderStatus[];
cancellation_statuses: CancellationStatus[];
search: string;
},
ctx: ApolloContext
) =>
Orders.count(args.statuses, args.cancellation_statuses, args.search, ctx),
},
Mutation: {
updateOrder: (
Expand Down
230 changes: 158 additions & 72 deletions app/(api)/_datalib/_services/Orders.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import revalidateCache from '@actions/revalidateCache';
import prisma from '../_prisma/client';
import { OrderInput, OrderProductInput } from '@datatypes/Order';
import {
CancellationStatus,
OrderInput,
OrderProductInput,
OrderStatus,
OrderUpdateInput,
} from '@datatypes/Order';
import { ApolloContext } from '../apolloServer';
import { Prisma } from '@prisma/client';
import Stripe from 'stripe';
Expand All @@ -14,7 +20,7 @@ export default class Orders {
data: {
...input, // Spread the input fields
total: 0,
status: 'pending', // Default status
status: OrderStatus.PENDING, // Default status
created_at: new Date(), // Current timestamp
},
});
Expand All @@ -34,20 +40,41 @@ export default class Orders {
}

static async findMany(
statuses: string[],
statuses: OrderStatus[],
cancellation_statuses: CancellationStatus[],
search: string,
offset: number,
limit: number,
ctx: ApolloContext
) {
if (!ctx.isOwner && !ctx.hasValidApiKey) return null;

if (offset < 0 || limit <= 0) return null;

const whereClause: Prisma.OrderWhereInput = {};
const queryConditions: Prisma.OrderWhereInput[] = [];

const statusFilters: Prisma.OrderWhereInput[] = [];
if (statuses?.length) {
statusFilters.push({ status: { in: statuses } });
}
if (cancellation_statuses?.length) {
statusFilters.push({
cancellation_status: { in: cancellation_statuses },
});
}

if (statuses && statuses.length > 0) {
whereClause.status = { in: statuses };
if (statusFilters.length > 1) {
queryConditions.push({ OR: statusFilters });
} else if (statusFilters.length === 1) {
queryConditions.push(statusFilters[0]);
}

// For in progress requests, ensure there's no cancellation status.
const isInProgressRequest =
statuses?.length &&
!cancellation_statuses?.length &&
!statuses.includes(OrderStatus.DELIVERED);
if (isInProgressRequest) {
queryConditions.push({ cancellation_status: null });
}

if (search) {
Expand Down Expand Up @@ -75,19 +102,86 @@ export default class Orders {
});
}

whereClause.OR = searchConditions;
queryConditions.push({ OR: searchConditions });
}

return prisma.order.findMany({
where: whereClause,
where: { AND: queryConditions },
orderBy: {
created_at: 'desc',
},
skip: offset * limit,
skip: offset,
take: limit,
});
}

static async count(
statuses: OrderStatus[],
cancellation_statuses: CancellationStatus[],
search: string,
ctx: ApolloContext
) {
if (!ctx.isOwner && !ctx.hasValidApiKey) return null;

const queryConditions: Prisma.OrderWhereInput[] = [];

const statusFilters: Prisma.OrderWhereInput[] = [];
if (statuses?.length) {
statusFilters.push({ status: { in: statuses } });
}
if (cancellation_statuses?.length) {
statusFilters.push({
cancellation_status: { in: cancellation_statuses },
});
}

if (statusFilters.length > 1) {
queryConditions.push({ OR: statusFilters });
} else if (statusFilters.length === 1) {
queryConditions.push(statusFilters[0]);
}

const isInProgressRequest =
statuses?.length &&
!cancellation_statuses?.length &&
!statuses.includes(OrderStatus.DELIVERED);
if (isInProgressRequest) {
queryConditions.push({ cancellation_status: null });
}

if (search) {
const searchConditions: Prisma.OrderWhereInput[] = [
{ customer_name: { contains: search, mode: 'insensitive' } },
{ customer_email: { contains: search, mode: 'insensitive' } },
{ customer_phone_num: { contains: search, mode: 'insensitive' } },
];

const searchAsNumber = parseInt(search, 10);
if (!isNaN(searchAsNumber)) {
searchConditions.push({ id: searchAsNumber });
searchConditions.push({
id: {
in: await prisma.order
.findMany({
select: { id: true },
})
.then((orders) =>
orders
.filter((order) => order.id.toString().includes(search))
.map((order) => order.id)
),
},
});
}

queryConditions.push({ OR: searchConditions });
}

return prisma.order.count({
where: { AND: queryConditions },
});
}

static async getProducts(order_id: number, ctx: ApolloContext) {
if (!ctx.isOwner && !ctx.hasValidApiKey) return null;

Expand All @@ -109,7 +203,7 @@ export default class Orders {
}

//UPDATE
static async update(id: number, input: OrderInput, ctx: ApolloContext) {
static async update(id: number, input: OrderUpdateInput, ctx: ApolloContext) {
if (!ctx.isOwner && !ctx.hasValidApiKey) return null;

try {
Expand Down Expand Up @@ -283,12 +377,12 @@ export default class Orders {
id,
},
select: {
status: true,
cancellation_status: true,
},
});

if (order) {
if (order.status == 'refunded') {
if (order.cancellation_status == 'REFUNDED') {
await prisma.order.delete({
where: {
id,
Expand All @@ -302,7 +396,7 @@ export default class Orders {
id,
},
data: {
status: 'needs refund',
cancellation_status: CancellationStatus.CANCELLED,
},
});
// could possibly add a message? "this order need to be refunded" or smth
Expand All @@ -321,70 +415,62 @@ export default class Orders {
products: OrderProductInput[],
ctx: ApolloContext
) {
if (!ctx.isOwner && !ctx.hasValidApiKey) return null;

try {
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2025-05-28.basil', // explicitly set the API version
});

// Lookup product prices from DB
const productIds = products.map((p) => p.product_id);
const dbProducts = await prisma.product.findMany({
where: { id: { in: productIds } },
});

const productMap = Object.fromEntries(dbProducts.map((p) => [p.id, p]));

const total = products.reduce((sum, item) => {
const product = productMap[item.product_id];
return sum + (product?.price ?? 0) * item.quantity;
}, 0);
if (!ctx.isOwner && !ctx.hasValidApiKey) {
throw new Error('Unauthorized');
}

// Stripe counts payment amounts in cents
const amountInCents = Math.round(total * 100);
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY as string, {
apiVersion: '2025-05-28.basil',
});

// Create the order
const createdOrder = await prisma.order.create({
data: {
...input,
total: total,
status: 'pending',
created_at: new Date(),
products: {
create: products.map((p) => ({
quantity: p.quantity,
product: { connect: { id: p.product_id } },
})),
},
},
include: { products: { include: { product: true } } },
});
let total = 0;
await Promise.all(
products.map(async (p) => {
const product = await prisma.product.findUnique({
where: { id: p.product_id },
});
if (!product) {
throw new Error(`Product with ID ${p.product_id} not found`);
}
total += (product.price - (product.discount ?? 0)) * p.quantity;
})
);

// Create Stripe PaymentIntent
const paymentIntent = await stripe.paymentIntents.create({
amount: amountInCents,
currency: 'usd',
metadata: {
orderId: createdOrder.id,
const order = await prisma.order.create({
data: {
...input,
total,
status: OrderStatus.ORDERED,
created_at: new Date(),
products: {
create: products.map((p) => ({
product_id: p.product_id,
quantity: p.quantity,
})),
},
});
},
include: {
products: true,
},
});

// Save paymentIntentId to order
const updatedOrder = await prisma.order.update({
where: { id: createdOrder.id },
data: { paymentIntentId: paymentIntent.id },
include: { products: { include: { product: true } } },
});
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(total * 100),
currency: 'usd',
metadata: {
orderId: order.id,
},
});

revalidateCache(['orders', 'products']);
await prisma.order.update({
where: { id: order.id },
data: { paymentIntentId: paymentIntent.id },
});

return {
order: updatedOrder,
clientSecret: paymentIntent.client_secret,
};
} catch (e) {
return e;
}
revalidateCache(['orders']);
return {
order,
clientSecret: paymentIntent.client_secret,
};
}
}
Loading