Kit de tienda online para Next.js: catálogo, carrito, pago con Stripe, pedidos, envíos, cupones, reseñas y cuentas
Instalar
genpm add @core/kit-storeQué obtienes
- Código en src/app/(store)/, 27 archivos. (57,2 kB)
- Reglas de IA en src/app/(store)/AGENTS.md, más archivos de reglas para tu IDE.
- Variables añadidas a .env.example: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, CART_COOKIE_SECRET, ORDER_LINK_SECRET, STORE_CURRENCY.
- Resuelve @core/cart, @core/catalog, @core/checkout, @core/discounts, @core/kit-cms, @core/orders, @core/reviews, @core/shipping por ti.
README
Este paquete no tiene README.
Esto es exactamente lo que lee tu IA cuando trabaja en src/app/(store). No se añade nada más a su contexto.
@core/kit-store — rules for AI agents
Purpose
An online store on top of @core/kit-cms, managed from the same /admin: products with variants and categories,
cart, Stripe Checkout, orders (created only by the Stripe webhook), shipping zones and rates, discount codes,
verified reviews, customer orders page, transactional emails and SEO (Product JSON-LD, sitemap). Every storefront
form is a Next.js Server Action, so it works without JavaScript and never accepts prices from the browser.
Map
_templates/genpm.md— the exact lines this kit adds to the project'ssrc/genpm/*.ts(generated, always current)._lib/maintenance.ts— dailystore.maintenancejob (deletes expired carts).shop/page.tsx,categories/[slug],collections/[slug]— listings.products/[slug]/page.tsx— product page.cart/page.tsx— cart, discount code, shipping country/method, totals and payment.checkout/success— real status.orders/[number]/page.tsx— order for its owner or with the signed email link.account/page.tsx— customer orders.api/stripe/webhook/route.ts— Stripe webhook (@core/stripe)._lib/actions.ts— server actions (add, update, code, shipping, checkout, review)._lib/store.ts— helpers._components/— product card/grid, add to cart,CartLinkfor the header, reviews, order summary,store.css._blocks/products.tsx— "Product grid" and "Buy now" blocks._lib/widgets.ts— sales, orders to ship, low stock._lib/legal.ts+_scripts/seed-legal.ts— legal pages as drafts pending review, with a dashboard warning.
Integration
- @core/kit-cms must be integrated first.
- Env:
STRIPE_SECRET_KEY,STRIPE_WEBHOOK_SECRET,CART_COOKIE_SECRETandORDER_LINK_SECRET(≥ 32 chars),STORE_CURRENCY(e.g.EUR),SITE_URL,EMAIL_FROM. Use Stripe test mode until the end-to-end check passes. If the Stripe MCP server is available and the person agrees, use it to inspect the test account (never live keys). - Migrations for catalog, cart, checkout, orders, shipping, discounts, reviews, comments and stripe.
- Add every line of
_templates/genpm.mdto the project'ssrc/genpm/*.ts(it says which file and where): it createssrc/genpm/commerce.ts(imports that register webhooks, cart steps and the dailystore.maintenancejob), the product sitemap and search sources, theproductGrid/buyNowblocks, and the admin resources and widgets (including comments, where product reviews are moderated). Then run the kit-cmssetup-schedules.tsagain. - Stripe webhook: endpoint
https://<site>/api/stripe/webhookwithcheckout.session.completed,checkout.session.async_payment_succeededandcheckout.session.expired(refunds are started from the admin); locallystripe listen --forward-to localhost:3000/api/stripe/webhook. - Create shipping zones and rates in the admin; put
<CartLink />in the site header and "Shop" in the menu. - The person runs
npx tsx "src/app/(store)/_scripts/seed-legal.ts": terms, shipping, returns/withdrawal, privacy and cookies are created as drafts. They must complete them and have them reviewed before publishing. - Verify in test mode: buy with card 4242 4242 4242 4242, the webhook creates the order, the email arrives, stock decreases, the order page opens from the email link and not without it.
Conventions
- Prices are integers in minor units; the client only sends variant ids, quantities, codes and the shipping choice.
- Orders exist only after Stripe confirms payment (webhook), never from the success page.
- The "before" price is hidden: in the EU it must be the lowest price of the previous 30 days (Omnibus directive).
With @core/pricing installed, show it only through
honestCompareAt.
Don't
- Don't publish legal pages the person has not reviewed, and never present generated legal text as final.
- Don't show fake reviews, ratings, stock counts or countdowns; review JSON-LD only with real approved reviews.
- Don't expose order pages without the owner session or the signed token; don't put tokens in analytics.
# @core/kit-store — rules for AI agents
## Purpose
An online store on top of @core/kit-cms, managed from the same `/admin`: products with variants and categories,
cart, Stripe Checkout, orders (created only by the Stripe webhook), shipping zones and rates, discount codes,
verified reviews, customer orders page, transactional emails and SEO (Product JSON-LD, sitemap). Every storefront
form is a Next.js Server Action, so it works without JavaScript and never accepts prices from the browser.
## Map
- `_templates/genpm.md` — the exact lines this kit adds to the project's `src/genpm/*.ts` (generated, always current).
- `_lib/maintenance.ts` — daily `store.maintenance` job (deletes expired carts).
- `shop/page.tsx`, `categories/[slug]`, `collections/[slug]` — listings. `products/[slug]/page.tsx` — product page.
- `cart/page.tsx` — cart, discount code, shipping country/method, totals and payment. `checkout/success` — real status.
- `orders/[number]/page.tsx` — order for its owner or with the signed email link. `account/page.tsx` — customer orders.
- `api/stripe/webhook/route.ts` — Stripe webhook (@core/stripe).
- `_lib/actions.ts` — server actions (add, update, code, shipping, checkout, review). `_lib/store.ts` — helpers.
- `_components/` — product card/grid, add to cart, `CartLink` for the header, reviews, order summary, `store.css`.
- `_blocks/products.tsx` — "Product grid" and "Buy now" blocks. `_lib/widgets.ts` — sales, orders to ship, low stock.
- `_lib/legal.ts` + `_scripts/seed-legal.ts` — legal pages as drafts pending review, with a dashboard warning.
## Integration
1. @core/kit-cms must be integrated first.
2. Env: `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET`, `CART_COOKIE_SECRET` and `ORDER_LINK_SECRET` (≥ 32 chars),
`STORE_CURRENCY` (e.g. `EUR`), `SITE_URL`, `EMAIL_FROM`. Use Stripe test mode until the end-to-end check passes.
If the Stripe MCP server is available and the person agrees, use it to inspect the test account (never live keys).
3. Migrations for catalog, cart, checkout, orders, shipping, discounts, reviews, comments and stripe.
4. Add every line of `_templates/genpm.md` to the project's `src/genpm/*.ts` (it says which file and where): it creates
`src/genpm/commerce.ts` (imports that register webhooks, cart steps and the daily `store.maintenance` job), the
product sitemap and search sources, the `productGrid` / `buyNow` blocks, and the admin resources and widgets
(including comments, where product reviews are moderated). Then run the kit-cms `setup-schedules.ts` again.
5. Stripe webhook: endpoint `https://<site>/api/stripe/webhook` with `checkout.session.completed`,
`checkout.session.async_payment_succeeded` and `checkout.session.expired` (refunds are started from the admin); locally `stripe listen --forward-to localhost:3000/api/stripe/webhook`.
6. Create shipping zones and rates in the admin; put `<CartLink />` in the site header and "Shop" in the menu.
7. The person runs `npx tsx "src/app/(store)/_scripts/seed-legal.ts"`: terms, shipping, returns/withdrawal, privacy
and cookies are created as drafts. They must complete them and have them reviewed before publishing.
8. Verify in test mode: buy with card 4242 4242 4242 4242, the webhook creates the order, the email arrives, stock
decreases, the order page opens from the email link and not without it.
## Conventions
- Prices are integers in minor units; the client only sends variant ids, quantities, codes and the shipping choice.
- Orders exist only after Stripe confirms payment (webhook), never from the success page.
- The "before" price is hidden: in the EU it must be the lowest price of the previous 30 days (Omnibus directive).
With @core/pricing installed, show it only through `honestCompareAt`.
## Don't
- Don't publish legal pages the person has not reviewed, and never present generated legal text as final.
- Don't show fake reviews, ratings, stock counts or countdowns; review JSON-LD only with real approved reviews.
- Don't expose order pages without the owner session or the signed token; don't put tokens in analytics.
El árbol exacto que se inyectará, tras aplicar .genpmignore. Anclado a
'use server';
// Acciones de servidor de la tienda: funcionan sin JavaScript (formularios HTML) y nunca aceptan precios del cliente:
// el carrito guarda variantes y cantidades; los importes los calcula el servidor (@core/cart, @core/checkout).
import { headers } from 'next/headers';
import { redirect } from 'next/navigation';
import { currentUser } from '@/app/(cms)/_lib/session';
import { addLine, CartError, getCart, getOrCreateCart, setCartMeta, setDiscountCodes, setLine } from '@/lib/cart';
import { CheckoutError, startCheckout } from '@/lib/checkout';
import { postReview } from '@/lib/reviews';
import { applySetCookie, cookieHeader, currentUserId } from './store';
const str = (fd: FormData, k: string, max = 200) => String(fd.get(k) ?? '').trim().slice(0, max);
const back = (path: string, params: Record<string, string>) => `${path}?${new URLSearchParams(params)}`;
/** Ruta local del mismo sitio (sin `//host` ni `/\\host`), sin query; si no, `fallback`. */
const localPath = (p: string, fallback: string) => {
const path = p.split(/[?#]/)[0]!;
return /^\/(?![/\\])/.test(path) && !path.includes('\\') ? path : fallback;
};
async function cart() {
const { cart: c, setCookie } = await getOrCreateCart(await cookieHeader(), await currentUserId());
await applySetCookie(setCookie);
return c;
}
export async function addToCart(fd: FormData): Promise<void> {
const variantId = str(fd, 'variantId', 64);
const quantity = Math.min(Math.max(Number(fd.get('quantity') ?? 1) || 1, 1), 99);
const from = str(fd, 'from', 300);
try {
await addLine((await cart()).id, variantId, quantity);
} catch (e) {
if (e instanceof CartError) redirect(back(localPath(from, '/shop'), { cart_error: e.code }));
throw e;
}
redirect('/cart?added=1');
}
export async function updateLine(fd: FormData): Promise<void> {
const c = await getCart(await cookieHeader(), await currentUserId());
if (c) {
const quantity = Math.min(Math.max(Math.floor(Number(fd.get('quantity'))) || 0, 0), 99);
try {
await setLine(c.id, str(fd, 'variantId', 64), quantity);
} catch (e) {
if (!(e instanceof CartError)) throw e;
redirect(back('/cart', { cart_error: e.code }));
}
}
redirect('/cart');
}
export async function applyCode(fd: FormData): Promise<void> {
const c = await cart();
const code = str(fd, 'code', 40);
await setDiscountCodes(c.id, code ? [code] : []);
redirect('/cart');
}
export async function setShipping(fd: FormData): Promise<void> {
const c = await cart();
const country = str(fd, 'country', 2).toUpperCase();
const rate = str(fd, 'shippingRateId', 64);
await setCartMeta(c.id, { ...(/^[A-Z]{2}$/.test(country) && { country }), ...(rate && { shippingRateId: rate }) });
redirect('/cart');
}
/** Crea la sesión de Stripe Checkout con los totales del servidor y redirige a Stripe. */
export async function checkout(fd: FormData): Promise<void> {
const c = await getCart(await cookieHeader(), await currentUserId());
if (!c) redirect('/cart');
const site = new URL(process.env.SITE_URL ?? 'http://localhost:3000').origin;
let url: string;
try {
({ url } = await startCheckout({ cart: c, email: str(fd, 'email', 254), successUrl: `${site}/checkout/success`, cancelUrl: `${site}/cart` }));
} catch (e) {
if (e instanceof CheckoutError) redirect(back('/cart', { checkout_error: e.code }));
throw e;
}
redirect(url);
}
/** Reseña de producto (moderada; se marca "compra verificada" si hay un pedido entregado). */
export async function submitReview(fd: FormData): Promise<void> {
const productId = str(fd, 'productId', 64);
const slug = str(fd, 'slug', 200);
const user = await currentUser();
try {
const r = await postReview(
{
productId,
rating: Number(fd.get('rating')),
body: str(fd, 'body', 5000),
...(user ? { user: { id: user.id, name: user.name ?? null } } : { guest: { name: str(fd, 'name', 80), email: str(fd, 'email', 254) } }),
},
{ headers: await headers(), fields: fd },
);
redirect(back(`/products/${encodeURIComponent(slug)}`, { review: r.status }) + '#reviews');
} catch (e) {
const code = (e as { code?: string }).code ?? ((e as Error).name === 'ZodError' ? 'invalid' : null);
if (!code) throw e;
redirect(back(`/products/${encodeURIComponent(slug)}`, { review: code }) + '#reviews');
}
}
Este paquete no declara servidores MCP.
| Versión | Commit | Publicado | Escaneo |
|---|---|---|---|
| 1.0.1 | 6a45dae | hace 6 horas | escaneo superado |
- genpm
- @core/cart ^1.0.0@core/catalog ^1.0.0@core/checkout ^1.0.0@core/discounts ^1.0.0@core/kit-cms ^1.0.0@core/orders ^1.0.0@core/reviews ^1.0.0@core/shipping ^1.0.0
- propuesta
- GenPM propone el comando npm y solo lo ejecuta si dices que sí.
- Usado por (1)
- @core/kit-dropshipping ^1.0.0
- escaneo
- escaneo superado · 0 hallazgos
- commit
- v1.0.1 → 6a45dae248ce17fbd95b5f3b2b61c68f66236041 · verificado tras la descarga
- scripts
- Ninguno. GenPM nunca ejecuta código del paquete.
- licencia
- MIT
- Calidad
- 100/100
- Licencia reconocidacumplido
- AGENTS.md explica su propósitocumplido
- AGENTS.md tiene pasos de integracióncumplido
- AGENTS.md lista convenciones o prohibicionescumplido
- Incluye testscumplido
- Escaneo de seguridad superadocumplido
- Publicado en los últimos 6 mesescumplido
- Publicador verificadocumplido
- Resumen y palabras clavecumplido
- reporte
- ¿Ves algo raro?