Kit de dropshipping para Next.js: importação de fornecedores, margens, landings de produto, repasse e exceções
Instalar
genpm add @core/kit-dropshippingO que você recebe
- Código em src/app/(dropshipping)/, 10 arquivos. (23,4 kB)
- Regras de IA em src/app/(dropshipping)/AGENTS.md, mais arquivos de regras da IDE.
- Variáveis de ambiente adicionadas ao .env.example: PAYMENT_FEE_BPS, PAYMENT_FEE_FIXED, SUPPLIERS_SYNC_CRON, SUPPLIERS_TRACKING_CRON.
- Resolve @core/kit-landing, @core/kit-store, @core/pricing, @core/suppliers para você.
README
Este pacote não tem README.
Isto é exatamente o que sua IA lê quando trabalha em src/app/(dropshipping). Nada mais é adicionado ao contexto dela.
@core/kit-dropshipping — rules for AI agents
Purpose
Dropshipping on top of @core/kit-store and @core/kit-landing (kit-cms arrives once through both): connect suppliers,
import products with their cost and a price from margin rules (@core/pricing), single-product landings at /p/<slug>
with direct "buy now" to Stripe, automatic or approved forwarding of paid orders to the supplier, tracking sync,
exceptions for what cannot be automated and an estimated profit widget. Logic lives in @core/suppliers and @core/pricing.
Map
_templates/genpm.md— the exact lines this kit adds to the project'ssrc/genpm/*.ts(generated, always current).p/[slug]/page.tsx— product landing: blocks of the landing with the same slug (optional), "buy now" form and delivery notice._lib/actions.ts—buyNowserver action (single-product cart, country, Stripe Checkout, attribution with consent)._lib/purchase.ts— serverpurchaseevent onpaid(Meta CAPI / TikTok / GA4 MP, only with consent)._components/delivery-notice.tsx— real delivery time, origin country, duties and returns, shown before payment._components/track-view.tsx— clientViewContentevent on/p/<slug>(only with marketing consent)._lib/widgets.ts— profit (7 days, estimated), supplier orders queue, open exceptions._scripts/setup-schedules.ts— schedules cost/stock sync (6 h) and tracking (12 h).
Integration
- @core/kit-store and @core/kit-landing must be integrated first (follow their AGENTS.md).
- Add the lines of
_templates/genpm.mdto the project'ssrc/genpm/*.ts(it says which file and where): imports incommerce.ts(pricing, suppliers and_lib/purchase, which registers the serverpurchaseevent when imported) and the admin resources and widgets. - Migrations for @core/suppliers and @core/pricing.
- Create a price rule (Admin → Price rules) before importing anything; imports fail without one.
- Start with the
manualadapter if there are no API credentials: Admin → Suppliers → new supplier (config:orderEmail,shipsFromas a 2-letter country code) → "Import products from CSV". Version 1.0 ships only themanualadapter; API adapters (CJ, AliExpress) will come as separate packages and will read their credentials from environment variables, never from the supplier config. - Products are imported as drafts: review texts, images (third-party rights) and prices, then activate them.
- Add
<DeliveryNotice product={p} />tosrc/app/(store)/products/[slug]/page.tsxnext to the add-to-cart form. - The person runs
npx tsx "src/app/(dropshipping)/_scripts/setup-schedules.ts";/api/cronmust run every minute. - Verify in Stripe test mode: buy from
/p/<slug>, the order appears in Supplier orders as pending approval, approve it, the supplier receives the order, add tracking, the customer receives the "shipped" email.
Conventions
- Forwarding starts in approval mode; enable
autoForwardper supplier only after a few correct orders. - Prices come from the rules and the cost; when the cost rises and the margin would be negative, the product is paused and an exception opens (never sell at a loss silently).
- The shop is the seller: it handles returns and the 14-day withdrawal right, whatever the supplier does.
Don't
- Don't hide delivery times, origin country or possible import charges until after payment (EU consumer law).
- Don't scrape suppliers or automate against their terms: official APIs or the manual adapter only.
- Don't import reviews without labelling them, invent features or certifications, or use fake urgency (see kit-landing).
# @core/kit-dropshipping — rules for AI agents
## Purpose
Dropshipping on top of @core/kit-store and @core/kit-landing (kit-cms arrives once through both): connect suppliers,
import products with their cost and a price from margin rules (@core/pricing), single-product landings at `/p/<slug>`
with direct "buy now" to Stripe, automatic or approved forwarding of paid orders to the supplier, tracking sync,
exceptions for what cannot be automated and an estimated profit widget. Logic lives in @core/suppliers and @core/pricing.
## Map
- `_templates/genpm.md` — the exact lines this kit adds to the project's `src/genpm/*.ts` (generated, always current).
- `p/[slug]/page.tsx` — product landing: blocks of the landing with the same slug (optional), "buy now" form and delivery notice.
- `_lib/actions.ts` — `buyNow` server action (single-product cart, country, Stripe Checkout, attribution with consent).
- `_lib/purchase.ts` — server `purchase` event on `paid` (Meta CAPI / TikTok / GA4 MP, only with consent).
- `_components/delivery-notice.tsx` — real delivery time, origin country, duties and returns, shown before payment.
- `_components/track-view.tsx` — client `ViewContent` event on `/p/<slug>` (only with marketing consent).
- `_lib/widgets.ts` — profit (7 days, estimated), supplier orders queue, open exceptions.
- `_scripts/setup-schedules.ts` — schedules cost/stock sync (6 h) and tracking (12 h).
## Integration
1. @core/kit-store and @core/kit-landing must be integrated first (follow their AGENTS.md).
2. Add the lines of `_templates/genpm.md` to the project's `src/genpm/*.ts` (it says which file and where): imports in
`commerce.ts` (pricing, suppliers and `_lib/purchase`, which registers the server `purchase` event when imported)
and the admin resources and widgets.
3. Migrations for @core/suppliers and @core/pricing.
4. Create a price rule (Admin → Price rules) before importing anything; imports fail without one.
5. Start with the `manual` adapter if there are no API credentials: Admin → Suppliers → new supplier (`config`:
`orderEmail`, `shipsFrom` as a 2-letter country code) → "Import products from CSV". Version 1.0 ships only the
`manual` adapter; API adapters (CJ, AliExpress) will come as separate packages and will read their credentials from
environment variables, never from the supplier config.
6. Products are imported as drafts: review texts, images (third-party rights) and prices, then activate them.
7. Add `<DeliveryNotice product={p} />` to `src/app/(store)/products/[slug]/page.tsx` next to the add-to-cart form.
8. The person runs `npx tsx "src/app/(dropshipping)/_scripts/setup-schedules.ts"`; `/api/cron` must run every minute.
9. Verify in Stripe test mode: buy from `/p/<slug>`, the order appears in Supplier orders as pending approval, approve
it, the supplier receives the order, add tracking, the customer receives the "shipped" email.
## Conventions
- Forwarding starts in approval mode; enable `autoForward` per supplier only after a few correct orders.
- Prices come from the rules and the cost; when the cost rises and the margin would be negative, the product is paused
and an exception opens (never sell at a loss silently).
- The shop is the seller: it handles returns and the 14-day withdrawal right, whatever the supplier does.
## Don't
- Don't hide delivery times, origin country or possible import charges until after payment (EU consumer law).
- Don't scrape suppliers or automate against their terms: official APIs or the manual adapter only.
- Don't import reviews without labelling them, invent features or certifications, or use fake urgency (see kit-landing).
A árvore exata que será injetada, após o .genpmignore. Fixada em
// Widgets del panel de dropshipping: rentabilidad estimada, cola de reenvío y excepciones abiertas.
import { and, count, eq, gte, inArray } from 'drizzle-orm';
import type { AdminWidget } from '@/lib/admin';
import { storeCurrency } from '@/lib/catalog';
import { getDb } from '@/lib/db';
import { format, money } from '@/lib/money';
import { orderLines, orders } from '@/lib/orders';
import { supplierExceptions, supplierOrders, supplierProducts } from '@/lib/suppliers';
/** Comisión estimada de la pasarela por pedido (por defecto 1,5 % + 0,25; ajusta con PAYMENT_FEE_BPS y PAYMENT_FEE_FIXED). */
export const paymentFee = (total: number) => Math.round((total * Number(process.env.PAYMENT_FEE_BPS ?? 150)) / 10_000) + Number(process.env.PAYMENT_FEE_FIXED ?? 25);
/** Rentabilidad de los pedidos pagados desde `from`: ingresos − coste del proveedor − comisión estimada. */
export async function profitSince(from: Date) {
const db = getDb();
const paid = await db
.select({ id: orders.id, total: orders.total, refunded: orders.refundedTotal, currency: orders.currency })
.from(orders)
.where(and(inArray(orders.status, ['paid', 'partially_refunded']), gte(orders.createdAt, from)));
if (!paid.length) return { orders: 0, revenue: 0, cost: 0, fees: 0, profit: 0, unknownCost: 0 };
const lines = await db
.select({ orderId: orderLines.orderId, quantity: orderLines.quantity, cost: supplierProducts.cost, costCurrency: supplierProducts.currency })
.from(orderLines)
.leftJoin(supplierProducts, eq(supplierProducts.variantId, orderLines.variantId))
.where(inArray(orderLines.orderId, paid.map((o) => o.id)));
let revenue = 0;
let cost = 0;
let fees = 0;
let unknownCost = 0;
for (const o of paid) {
revenue += o.total - o.refunded;
fees += paymentFee(o.total);
for (const l of lines.filter((x) => x.orderId === o.id)) {
if (l.cost == null || l.costCurrency !== o.currency) unknownCost += l.quantity;
else cost += l.cost * l.quantity;
}
}
return { orders: paid.length, revenue, cost, fees, profit: revenue - cost - fees, unknownCost };
}
export const dropshippingWidgets: AdminWidget[] = [
{
name: 'profit-7d',
title: 'Profit, 7 days (estimated)',
permission: 'orders:read',
async load() {
const r = await profitSince(new Date(Date.now() - 7 * 86_400_000));
const m = (n: number) => format(money(n, storeCurrency()));
return {
rows: [
{ label: `Revenue (${r.orders} orders)`, value: m(r.revenue) },
{ label: 'Supplier cost', value: m(r.cost) },
{ label: 'Payment fees (est.)', value: m(r.fees) },
{ label: r.unknownCost ? `Profit (${r.unknownCost} items without cost)` : 'Profit', value: m(r.profit) },
],
};
},
},
{
name: 'forwarding',
title: 'Supplier orders',
permission: 'suppliers:read',
async load() {
const rows = await getDb().select({ status: supplierOrders.status, n: count() }).from(supplierOrders).where(inArray(supplierOrders.status, ['pending_approval', 'queued', 'failed'])).groupBy(supplierOrders.status);
return { rows: rows.map((r) => ({ label: r.status.replace('_', ' '), value: r.n, href: '/admin/supplier-orders' })) };
},
},
{
name: 'exceptions',
title: 'Open exceptions',
permission: 'suppliers:read',
async load() {
const [r] = await getDb().select({ n: count() }).from(supplierExceptions).where(eq(supplierExceptions.status, 'open'));
return { value: r?.n ?? 0 };
},
},
];
Este pacote não declara servidores MCP.
| Versão | Commit | Publicado | Análise |
|---|---|---|---|
| 1.0.1 | a15c9c8 | há 3 horas | análise aprovada |
- proposto
- O GenPM propõe o comando npm e só o executa se você disser sim.
- Usado por (0)
- Nenhum pacote público depende dele ainda.
- análise
- análise aprovada · 0 achados
- commit
- v1.0.1 → a15c9c8fd298cfa638e5b677485732213d13a05a · verificado após o download
- scripts
- Nenhum. O GenPM nunca executa código de pacotes.
- licença
- MIT
- Qualidade
- 100/100
- Licença reconhecidacumprido
- AGENTS.md explica o propósitocumprido
- AGENTS.md tem passos de integraçãocumprido
- AGENTS.md lista convenções ou proibiçõescumprido
- Inclui testescumprido
- Escaneamento de segurança aprovadocumprido
- Publicado nos últimos 6 mesescumprido
- Publicador verificadocumprido
- Resumo e palavras-chavecumprido
- denúncia
- Viu algo errado?