()
| 60 | }); |
| 61 | |
| 62 | async function main() { |
| 63 | // 1. Find the price by lookup key |
| 64 | const prices = await stripe.prices.list({ |
| 65 | lookup_keys: [LOOKUP_KEY], |
| 66 | active: true, |
| 67 | expand: ['data.product'], |
| 68 | }); |
| 69 | |
| 70 | if (prices.data.length === 0) { |
| 71 | console.error(`No active price found for lookup key: ${LOOKUP_KEY}`); |
| 72 | process.exit(1); |
| 73 | } |
| 74 | |
| 75 | const price = prices.data[0]; |
| 76 | const product = price.product as Stripe.Product; |
| 77 | console.log(`Product: ${product.name} (${price.lookup_key})`); |
| 78 | console.log(`Amount: ${(price.unit_amount! / 100).toFixed(2)} ${price.currency.toUpperCase()}`); |
| 79 | console.log(`Invoice date: ${INVOICE_DATE.toISOString().split('T')[0]}`); |
| 80 | console.log(`Terms: net-${DAYS_UNTIL_DUE}`); |
| 81 | |
| 82 | if (dryRun) { |
| 83 | console.log('\n--dry-run: Would create subscription + backdated invoice. Exiting.'); |
| 84 | return; |
| 85 | } |
| 86 | |
| 87 | // 2. Find or create customer |
| 88 | const existing = await stripe.customers.list({ email: CUSTOMER_EMAIL, limit: 1 }); |
| 89 | let customer: Stripe.Customer; |
| 90 | |
| 91 | if (existing.data.length > 0) { |
| 92 | customer = existing.data[0]; |
| 93 | console.log(`\nFound existing customer: ${customer.id}`); |
| 94 | } else { |
| 95 | customer = await stripe.customers.create({ |
| 96 | email: CUSTOMER_EMAIL, |
| 97 | name: COMPANY_NAME, |
| 98 | metadata: { contact_name: CONTACT_NAME }, |
| 99 | }); |
| 100 | console.log(`\nCreated customer: ${customer.id}`); |
| 101 | } |
| 102 | |
| 103 | // 3. Create subscription with backdated start and custom terms |
| 104 | const invoiceDateUnix = Math.floor(INVOICE_DATE.getTime() / 1000); |
| 105 | |
| 106 | const subscription = await stripe.subscriptions.create({ |
| 107 | customer: customer.id, |
| 108 | items: [{ price: price.id }], |
| 109 | collection_method: 'send_invoice', |
| 110 | days_until_due: DAYS_UNTIL_DUE, |
| 111 | backdate_start_date: invoiceDateUnix, |
| 112 | metadata: { |
| 113 | lookup_key: LOOKUP_KEY, |
| 114 | contact_name: CONTACT_NAME, |
| 115 | note: 'Backdated invoice created via script', |
| 116 | }, |
| 117 | }); |
| 118 | |
| 119 | console.log(`\nSubscription created: ${subscription.id}`); |
no test coverage detected