Add admin and customer interfaces, orders, signed activation and leases, protected package delivery, keyring verification, migrations, security controls, tests and deployment documentation. Co-Authored-By: Craft Agent <agents-noreply@craft.do>
347 lines
12 KiB
Go
347 lines
12 KiB
Go
package httpapi
|
||
|
||
import (
|
||
"bytes"
|
||
"crypto/rand"
|
||
"crypto/sha256"
|
||
"database/sql"
|
||
"encoding/hex"
|
||
"encoding/json"
|
||
"errors"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
type orderRecord struct {
|
||
ID uint64 `json:"id"`
|
||
OrderNo string `json:"order_no"`
|
||
CustomerID uint64 `json:"customer_id"`
|
||
CustomerName string `json:"customer_name"`
|
||
ProductID uint64 `json:"product_id"`
|
||
ProductName string `json:"product_name"`
|
||
AmountCents uint64 `json:"amount_cents"`
|
||
Currency string `json:"currency"`
|
||
Status string `json:"status"`
|
||
PaymentReference *string `json:"payment_reference"`
|
||
PaidAt *time.Time `json:"paid_at"`
|
||
LicenseID *uint64 `json:"license_id"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
}
|
||
|
||
const orderSelect = `SELECT o.id,o.order_no,o.customer_id,c.name,o.product_id,p.name,o.amount_cents,o.currency,o.status,o.payment_reference,o.paid_at,o.issued_license_id,o.created_at,o.updated_at FROM offline_orders o JOIN customers c ON c.id=o.customer_id JOIN products p ON p.id=o.product_id`
|
||
|
||
type orderScanner interface{ Scan(...any) error }
|
||
|
||
func scanOrder(s orderScanner) (o orderRecord, err error) {
|
||
err = s.Scan(&o.ID, &o.OrderNo, &o.CustomerID, &o.CustomerName, &o.ProductID, &o.ProductName, &o.AmountCents, &o.Currency, &o.Status, &o.PaymentReference, &o.PaidAt, &o.LicenseID, &o.CreatedAt, &o.UpdatedAt)
|
||
return
|
||
}
|
||
func (a *BusinessAPI) listOrders(c *gin.Context) {
|
||
p, size := page(c)
|
||
var total int
|
||
if a.db.QueryRowContext(c, "SELECT COUNT(*) FROM offline_orders").Scan(&total) != nil {
|
||
apiError(c, 500, "internal_error", "订单加载失败")
|
||
return
|
||
}
|
||
rows, err := a.db.QueryContext(c, orderSelect+" ORDER BY o.id DESC LIMIT ? OFFSET ?", size, (p-1)*size)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "订单加载失败")
|
||
return
|
||
}
|
||
defer rows.Close()
|
||
out := []orderRecord{}
|
||
for rows.Next() {
|
||
o, e := scanOrder(rows)
|
||
if e != nil {
|
||
apiError(c, 500, "internal_error", "订单加载失败")
|
||
return
|
||
}
|
||
out = append(out, o)
|
||
}
|
||
if rows.Err() != nil {
|
||
apiError(c, 500, "internal_error", "订单加载失败")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": out, "meta": gin.H{"page": p, "page_size": size, "total": total}})
|
||
}
|
||
func (a *BusinessAPI) getOrder(c *gin.Context) {
|
||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||
if err != nil || id == 0 {
|
||
apiError(c, 400, "invalid_request", "订单 ID 无效")
|
||
return
|
||
}
|
||
o, err := scanOrder(a.db.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
apiError(c, 404, "not_found", "订单不存在")
|
||
return
|
||
}
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "订单加载失败")
|
||
return
|
||
}
|
||
c.JSON(200, gin.H{"data": o})
|
||
}
|
||
|
||
type orderInput struct {
|
||
CustomerID uint64 `json:"customer_id"`
|
||
ProductID uint64 `json:"product_id"`
|
||
AmountCents uint64 `json:"amount_cents"`
|
||
Currency string `json:"currency"`
|
||
PaymentReference string `json:"payment_reference"`
|
||
StartsAt string `json:"starts_at"`
|
||
ExpiresAt string `json:"expires_at"`
|
||
}
|
||
|
||
func (a *BusinessAPI) writeOrder(c *gin.Context, operation string) {
|
||
key, ok := parseOperationKey(c)
|
||
if !ok {
|
||
return
|
||
}
|
||
for _, r := range key {
|
||
if r < 33 || r > 126 {
|
||
apiError(c, 400, "invalid_idempotency_key", "幂等键仅允许可见 ASCII 字符")
|
||
return
|
||
}
|
||
}
|
||
var in orderInput
|
||
if c.ShouldBindJSON(&in) != nil {
|
||
apiError(c, 400, "invalid_request", "订单参数无效")
|
||
return
|
||
}
|
||
var id uint64
|
||
var err error
|
||
if operation != "create" {
|
||
id, err = strconv.ParseUint(c.Param("id"), 10, 64)
|
||
if err != nil || id == 0 {
|
||
apiError(c, 400, "invalid_request", "订单 ID 无效")
|
||
return
|
||
}
|
||
}
|
||
var starts, expires time.Time
|
||
switch operation {
|
||
case "create":
|
||
if in.CustomerID == 0 || in.ProductID == 0 || in.AmountCents == 0 || in.AmountCents > 100000000000 || in.Currency != "CNY" {
|
||
apiError(c, 400, "invalid_request", "客户产品必填,金额须为1至100000000000分,币种为CNY")
|
||
return
|
||
}
|
||
in = orderInput{CustomerID: in.CustomerID, ProductID: in.ProductID, AmountCents: in.AmountCents, Currency: in.Currency}
|
||
case "confirm-payment":
|
||
in.PaymentReference = strings.TrimSpace(in.PaymentReference)
|
||
if in.AmountCents == 0 || len(in.PaymentReference) == 0 || len(in.PaymentReference) > 190 {
|
||
apiError(c, 400, "invalid_request", "实际收款金额和收款凭据编号必填(编号最多190字节)")
|
||
return
|
||
}
|
||
in = orderInput{AmountCents: in.AmountCents, PaymentReference: in.PaymentReference}
|
||
case "issue":
|
||
starts, err = time.Parse(time.RFC3339, in.StartsAt)
|
||
if err != nil {
|
||
apiError(c, 400, "invalid_request", "开始时间必须为RFC3339")
|
||
return
|
||
}
|
||
expires, err = time.Parse(time.RFC3339, in.ExpiresAt)
|
||
starts = starts.UTC().Truncate(time.Microsecond)
|
||
expires = expires.UTC().Truncate(time.Microsecond)
|
||
if err != nil || !expires.After(starts) || starts.Before(time.Unix(1, 0)) || !expires.Before(time.Date(2038, 1, 19, 3, 14, 7, 0, time.UTC)) {
|
||
apiError(c, 400, "invalid_request", "授权期限无效或超出TIMESTAMP范围")
|
||
return
|
||
}
|
||
in = orderInput{StartsAt: starts.Format(time.RFC3339Nano), ExpiresAt: expires.Format(time.RFC3339Nano)}
|
||
default:
|
||
apiError(c, 400, "invalid_request", "未知订单操作")
|
||
return
|
||
}
|
||
payload, _ := json.Marshal(struct {
|
||
ID uint64
|
||
Input orderInput
|
||
}{id, in})
|
||
fingerprint := sha256.Sum256(payload)
|
||
tx, err := a.db.BeginTx(c, nil)
|
||
if err != nil {
|
||
apiError(c, 500, "internal_error", "服务暂时不可用")
|
||
return
|
||
}
|
||
defer tx.Rollback()
|
||
fail := func() { apiError(c, 500, "internal_error", "订单操作失败,请保留相同幂等键重试") }
|
||
actor := c.MustGet("admin_id")
|
||
// Consistent administrator-first lock order serializes same-actor retry keys across orders.
|
||
var locked uint64
|
||
err = tx.QueryRowContext(c, "SELECT id FROM admins WHERE id=? AND active=1 AND role='admin' FOR UPDATE", actor).Scan(&locked)
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
apiError(c, 403, "forbidden", "无权操作订单")
|
||
return
|
||
}
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
var storedFingerprint, storedResponse []byte
|
||
err = tx.QueryRowContext(c, "SELECT request_fingerprint,response FROM order_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", actor, operation, key).Scan(&storedFingerprint, &storedResponse)
|
||
if err == nil {
|
||
if !bytes.Equal(storedFingerprint, fingerprint[:]) {
|
||
apiError(c, 409, "idempotency_conflict", "同一幂等键不能用于不同订单请求")
|
||
return
|
||
}
|
||
var result gin.H
|
||
if json.Unmarshal(storedResponse, &result) != nil {
|
||
fail()
|
||
return
|
||
}
|
||
result["idempotent_replay"] = true
|
||
c.JSON(200, result)
|
||
return
|
||
}
|
||
if !errors.Is(err, sql.ErrNoRows) {
|
||
fail()
|
||
return
|
||
}
|
||
var o orderRecord
|
||
if operation != "create" {
|
||
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=? FOR UPDATE", id))
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
apiError(c, 404, "not_found", "订单不存在")
|
||
return
|
||
}
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
}
|
||
var license *licenseRecord
|
||
if operation == "create" || operation == "issue" {
|
||
customerID, productID := o.CustomerID, o.ProductID
|
||
if operation == "create" {
|
||
customerID, productID = in.CustomerID, in.ProductID
|
||
}
|
||
var customerStatus string
|
||
var active bool
|
||
err = tx.QueryRowContext(c, "SELECT name,status FROM customers WHERE id=? FOR UPDATE", customerID).Scan(&o.CustomerName, &customerStatus)
|
||
if errors.Is(err, sql.ErrNoRows) || err == nil && customerStatus != "active" {
|
||
apiError(c, 400, "inactive_or_missing_master_data", "客户不存在或未启用")
|
||
return
|
||
}
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
err = tx.QueryRowContext(c, "SELECT name,active FROM products WHERE id=? FOR UPDATE", productID).Scan(&o.ProductName, &active)
|
||
if errors.Is(err, sql.ErrNoRows) || err == nil && !active {
|
||
apiError(c, 400, "inactive_or_missing_master_data", "产品不存在或未启用")
|
||
return
|
||
}
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
}
|
||
switch operation {
|
||
case "create":
|
||
raw := make([]byte, 16)
|
||
if _, err = rand.Read(raw); err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
res, e := tx.ExecContext(c, "INSERT INTO offline_orders(order_no,customer_id,product_id,amount_cents,currency,created_by) VALUES(?,?,?,?,?,?)", hex.EncodeToString(raw), in.CustomerID, in.ProductID, in.AmountCents, in.Currency, actor)
|
||
if e != nil {
|
||
fail()
|
||
return
|
||
}
|
||
n, e := res.LastInsertId()
|
||
if e != nil {
|
||
fail()
|
||
return
|
||
}
|
||
id = uint64(n)
|
||
case "confirm-payment":
|
||
if o.Status != "pending_payment" {
|
||
apiError(c, 409, "invalid_state", "只有待收款订单可确认收款")
|
||
return
|
||
}
|
||
if o.AmountCents != in.AmountCents {
|
||
apiError(c, 400, "amount_mismatch", "实际收款必须等于订单金额")
|
||
return
|
||
}
|
||
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='paid',payment_reference=?,paid_at=?,paid_by=? WHERE id=?", in.PaymentReference, time.Now().UTC(), actor, id)
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
case "issue":
|
||
if o.Status != "paid" || o.LicenseID != nil {
|
||
apiError(c, 409, "invalid_state", "只有已收款且未发放的订单可发放授权")
|
||
return
|
||
}
|
||
raw := make([]byte, 16)
|
||
if _, err = rand.Read(raw); err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
// Random internal key avoids collisions with administrator-supplied direct-issuance keys.
|
||
internalKey := "order-" + strconv.FormatUint(id, 10) + "-" + hex.EncodeToString(raw)
|
||
res, e := tx.ExecContext(c, "INSERT INTO licenses(license_key,customer_id,product_id,status,starts_at,expires_at,idempotency_key,issued_by) VALUES(?,?,?,'active',?,?,?,?)", hex.EncodeToString(raw), o.CustomerID, o.ProductID, starts, expires, internalKey, actor)
|
||
if e != nil {
|
||
fail()
|
||
return
|
||
}
|
||
n, e := res.LastInsertId()
|
||
if e != nil {
|
||
fail()
|
||
return
|
||
}
|
||
_, err = tx.ExecContext(c, "UPDATE offline_orders SET status='issued',issued_license_id=? WHERE id=?", n, id)
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
l := licenseRecord{}
|
||
err = tx.QueryRowContext(c, `SELECT l.id,l.license_key,l.customer_id,c.name,l.product_id,p.name,p.code,l.status,l.starts_at,l.expires_at,l.created_at FROM licenses l JOIN customers c ON c.id=l.customer_id JOIN products p ON p.id=l.product_id WHERE l.id=?`, n).Scan(&l.ID, &l.LicenseKey, &l.CustomerID, &l.CustomerName, &l.ProductID, &l.ProductName, &l.ProductCode, &l.Status, &l.StartsAt, &l.ExpiresAt, &l.CreatedAt)
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
l.Status = currentLicenseStatus(l.Status, l.StartsAt, l.ExpiresAt, time.Now().UTC())
|
||
license = &l
|
||
details, _ := json.Marshal(gin.H{"order_id": id, "customer_id": o.CustomerID, "product_id": o.ProductID, "starts_at": starts, "expires_at": expires})
|
||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,'license.issued','license',?,?)", actor, n, details); err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
}
|
||
o, err = scanOrder(tx.QueryRowContext(c, orderSelect+" WHERE o.id=?", id))
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
result := gin.H{"data": o, "idempotent_replay": false}
|
||
if license != nil {
|
||
result["license"] = license
|
||
}
|
||
response, err := json.Marshal(result)
|
||
if err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
if _, err = tx.ExecContext(c, "INSERT INTO order_operations(order_id,actor_admin_id,operation,idempotency_key,request_fingerprint,response) VALUES(?,?,?,?,?,?)", id, actor, operation, key, fingerprint[:], response); err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
details, _ := json.Marshal(gin.H{"customer_id": o.CustomerID, "product_id": o.ProductID, "amount_cents": o.AmountCents, "currency": o.Currency, "license_id": o.LicenseID})
|
||
if _, err = tx.ExecContext(c, "INSERT INTO audit_events(actor_admin_id,action,resource_type,resource_id,details) VALUES(?,?,'order',?,?)", actor, "order."+operation, id, details); err != nil {
|
||
fail()
|
||
return
|
||
}
|
||
if tx.Commit() != nil {
|
||
fail()
|
||
return
|
||
}
|
||
if operation == "create" {
|
||
c.Header("Location", "/api/v1/orders/"+strconv.FormatUint(id, 10))
|
||
c.JSON(201, result)
|
||
} else {
|
||
c.JSON(200, result)
|
||
}
|
||
}
|