mirror of
https://github.com/xtr-dev/payload-billing.git
synced 2025-12-10 02:43:24 +00:00
feat: add automatic payment/invoice status sync and invoice view page
Core Plugin Enhancements: - Add afterChange hook to payments collection to auto-update linked invoice status to 'paid' when payment succeeds - Add afterChange hook to invoices collection for bidirectional payment-invoice relationship management - Add invoice status sync when manually marked as paid - Update plugin config types to support collection extension options Demo Application Features: - Add professional invoice view page with print-friendly layout (/invoice/[id]) - Add custom message field to payment creation form - Add invoice API endpoint to fetch complete invoice data with customer info - Add payment API endpoint to retrieve payment with invoice relationship - Update payment success page with "View Invoice" button - Implement beforeChange hook to copy custom message from payment metadata to invoice - Remove customer collection dependency - use direct customerInfo fields instead Documentation: - Update README with automatic status synchronization section - Add collection extension examples to demo README - Document new features: bidirectional relationships, status sync, invoice view Technical Improvements: - Fix total calculation in invoice API (use 'amount' field instead of 'total') - Add proper TypeScript types with CollectionSlug casting - Implement Next.js 15 async params pattern in API routes - Add customer name/email/company fields to payment creation form 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,10 @@ export async function POST(request: Request) {
|
||||
})
|
||||
|
||||
const body = await request.json()
|
||||
const { amount, currency, description } = body
|
||||
const { amount, currency, description, message, customerName, customerEmail, customerCompany } = body
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('Received payment request:', { amount, currency, customerName, customerEmail, customerCompany })
|
||||
|
||||
if (!amount || !currency) {
|
||||
return Response.json(
|
||||
@@ -17,7 +20,16 @@ export async function POST(request: Request) {
|
||||
)
|
||||
}
|
||||
|
||||
// Create a payment using the test provider
|
||||
if (!customerName || !customerEmail) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('Missing customer info:', { customerName, customerEmail })
|
||||
return Response.json(
|
||||
{ success: false, error: 'Customer name and email are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Create a payment first using the test provider
|
||||
const payment = await payload.create({
|
||||
collection: 'payments',
|
||||
data: {
|
||||
@@ -29,10 +41,42 @@ export async function POST(request: Request) {
|
||||
metadata: {
|
||||
source: 'demo-ui',
|
||||
createdAt: new Date().toISOString(),
|
||||
customMessage: message, // Store the custom message in metadata
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Create an invoice linked to the payment
|
||||
// The invoice's afterChange hook will automatically link the payment back to the invoice
|
||||
const invoice = await payload.create({
|
||||
collection: 'invoices',
|
||||
data: {
|
||||
payment: payment.id, // Link to the payment
|
||||
customerInfo: {
|
||||
name: customerName,
|
||||
email: customerEmail,
|
||||
company: customerCompany,
|
||||
},
|
||||
billingAddress: {
|
||||
line1: '123 Demo Street',
|
||||
city: 'Demo City',
|
||||
state: 'DC',
|
||||
postalCode: '12345',
|
||||
country: 'US',
|
||||
},
|
||||
currency,
|
||||
items: [
|
||||
{
|
||||
description: description || 'Demo payment',
|
||||
quantity: 1,
|
||||
unitAmount: amount,
|
||||
},
|
||||
],
|
||||
taxAmount: 0,
|
||||
status: 'open',
|
||||
},
|
||||
})
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
payment: {
|
||||
@@ -41,6 +85,7 @@ export async function POST(request: Request) {
|
||||
amount: payment.amount,
|
||||
currency: payment.currency,
|
||||
description: payment.description,
|
||||
invoiceId: invoice.id,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
|
||||
116
dev/app/api/demo/invoice/[id]/route.ts
Normal file
116
dev/app/api/demo/invoice/[id]/route.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import configPromise from '@payload-config'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const payload = await getPayload({
|
||||
config: configPromise,
|
||||
})
|
||||
|
||||
const { id: invoiceId } = await params
|
||||
|
||||
if (!invoiceId) {
|
||||
return Response.json(
|
||||
{ success: false, error: 'Invoice ID is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Fetch the invoice
|
||||
const invoice = await payload.findByID({
|
||||
collection: 'invoices',
|
||||
id: invoiceId,
|
||||
})
|
||||
|
||||
if (!invoice) {
|
||||
return Response.json(
|
||||
{ success: false, error: 'Invoice not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Get customer info - either from relationship or direct fields
|
||||
let customerInfo = null
|
||||
|
||||
if (invoice.customer) {
|
||||
// Try to fetch from customer relationship
|
||||
try {
|
||||
const customerData = await payload.findByID({
|
||||
collection: 'customers',
|
||||
id: typeof invoice.customer === 'object' ? invoice.customer.id : invoice.customer,
|
||||
})
|
||||
customerInfo = {
|
||||
name: customerData.name,
|
||||
email: customerData.email,
|
||||
phone: customerData.phone,
|
||||
company: customerData.company,
|
||||
taxId: customerData.taxId,
|
||||
billingAddress: customerData.address,
|
||||
}
|
||||
} catch (error) {
|
||||
// Customer not found or collection doesn't exist
|
||||
console.error('Failed to fetch customer:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to direct customerInfo fields if no customer relationship
|
||||
if (!customerInfo && invoice.customerInfo) {
|
||||
customerInfo = {
|
||||
name: invoice.customerInfo.name,
|
||||
email: invoice.customerInfo.email,
|
||||
phone: invoice.customerInfo.phone,
|
||||
company: invoice.customerInfo.company,
|
||||
taxId: invoice.customerInfo.taxId,
|
||||
billingAddress: invoice.billingAddress,
|
||||
}
|
||||
}
|
||||
|
||||
// Default customer if neither is available
|
||||
if (!customerInfo) {
|
||||
customerInfo = {
|
||||
name: 'Unknown Customer',
|
||||
email: 'unknown@example.com',
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate subtotal from items (or use stored subtotal)
|
||||
const subtotal = invoice.subtotal || invoice.items?.reduce((sum: number, item: any) => {
|
||||
return sum + (item.unitAmount * item.quantity)
|
||||
}, 0) || 0
|
||||
|
||||
const taxAmount = invoice.taxAmount || 0
|
||||
const total = invoice.amount || (subtotal + taxAmount)
|
||||
|
||||
// Prepare the response
|
||||
const invoiceData = {
|
||||
id: invoice.id,
|
||||
invoiceNumber: invoice.number || invoice.invoiceNumber,
|
||||
customer: customerInfo,
|
||||
currency: invoice.currency,
|
||||
items: invoice.items || [],
|
||||
subtotal,
|
||||
taxAmount,
|
||||
total,
|
||||
status: invoice.status,
|
||||
customMessage: invoice.customMessage,
|
||||
issuedAt: invoice.issuedAt,
|
||||
dueDate: invoice.dueDate,
|
||||
createdAt: invoice.createdAt,
|
||||
}
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
invoice: invoiceData,
|
||||
})
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to fetch invoice:', error)
|
||||
return Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch invoice',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
63
dev/app/api/demo/payment/[id]/route.ts
Normal file
63
dev/app/api/demo/payment/[id]/route.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import configPromise from '@payload-config'
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const payload = await getPayload({
|
||||
config: configPromise,
|
||||
})
|
||||
|
||||
const { id: paymentProviderId } = await params
|
||||
|
||||
if (!paymentProviderId) {
|
||||
return Response.json(
|
||||
{ success: false, error: 'Payment ID is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Find payment by providerId (the test provider uses this format)
|
||||
const payments = await payload.find({
|
||||
collection: 'payments',
|
||||
where: {
|
||||
providerId: {
|
||||
equals: paymentProviderId,
|
||||
},
|
||||
},
|
||||
limit: 1,
|
||||
})
|
||||
|
||||
if (!payments.docs.length) {
|
||||
return Response.json(
|
||||
{ success: false, error: 'Payment not found' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
const payment = payments.docs[0]
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
payment: {
|
||||
id: payment.id,
|
||||
providerId: payment.providerId,
|
||||
amount: payment.amount,
|
||||
currency: payment.currency,
|
||||
status: payment.status,
|
||||
description: payment.description,
|
||||
invoice: payment.invoice,
|
||||
metadata: payment.metadata,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to fetch payment:', error)
|
||||
return Response.json(
|
||||
{
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to fetch payment',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user