Files
quyun-v2/backend/database/migrations/20251230091905_create_coupons.sql
Rogee dbfb08ed37 feat: add coupon support to orders and create user_coupons model
- Added CouponID field to Order model to track used coupons.
- Updated order query generation to include CouponID.
- Introduced UserCoupon model to manage user coupon associations.
- Implemented query methods for UserCoupon to facilitate CRUD operations.
- Updated query context and default query setup to include UserCoupon.
2025-12-30 17:28:21 +08:00

46 lines
2.0 KiB
SQL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- +goose Up
-- +goose StatementBegin
CREATE TABLE "coupons" (
"id" BIGSERIAL PRIMARY KEY,
"tenant_id" BIGINT NOT NULL DEFAULT 0, -- 租户ID
"title" VARCHAR(255) NOT NULL, -- 优惠券标题
"description" TEXT, -- 优惠券描述
"type" VARCHAR(32) NOT NULL, -- 优惠券类型: fix_amount(固定金额), discount(折扣比率)
"value" BIGINT NOT NULL, -- 优惠券面值 (固定金额为分折扣比率为0-100)
"min_order_amount" BIGINT NOT NULL DEFAULT 0, -- 最低订单金额门槛 (分)
"max_discount" BIGINT, -- 最高抵扣金额 (分,针对折扣券)
"total_quantity" INTEGER NOT NULL DEFAULT 0, -- 发行总量
"used_quantity" INTEGER NOT NULL DEFAULT 0, -- 已使用数量
"start_at" TIMESTAMPTZ, -- 开始生效时间
"end_at" TIMESTAMPTZ, -- 过期失效时间
"created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX "idx_coupons_tenant_id" ON "coupons" ("tenant_id");
CREATE TABLE "user_coupons" (
"id" BIGSERIAL PRIMARY KEY,
"user_id" BIGINT NOT NULL, -- 用户ID
"coupon_id" BIGINT NOT NULL, -- 优惠券ID
"order_id" BIGINT, -- 使用该优惠券的订单ID
"status" VARCHAR(32) NOT NULL DEFAULT 'unused', -- 状态: unused(未使用), used(已使用), expired(已过期)
"used_at" TIMESTAMPTZ, -- 使用时间
"created_at" TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX "idx_user_coupons_user_id" ON "user_coupons" ("user_id");
CREATE INDEX "idx_user_coupons_coupon_id" ON "user_coupons" ("coupon_id");
-- Add CouponID to Orders table
ALTER TABLE "orders" ADD COLUMN "coupon_id" BIGINT DEFAULT 0; -- 关联优惠券ID (0表示未使用)
COMMENT ON COLUMN "orders"."coupon_id" IS '使用的优惠券ID (0表示未使用)';
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
ALTER TABLE "orders" DROP COLUMN IF EXISTS "coupon_id";
DROP TABLE IF EXISTS "user_coupons";
DROP TABLE IF EXISTS "coupons";
-- +goose StatementEnd