Files
sale/scripts/migrate_prices_to_jpy.py
T
Hermes ae37085e25
Build and Push Docker Image / build-and-push (push) Successful in 8s
Build and Push Docker Image / deploy (push) Successful in 8s
i18n(content): 库里的运营内容日文化(分类/轮播/公告/活动/资讯/单位/描述)
代码里的界面文案日文化不等于站点日文化 —— 首页 banner、活动标题、资讯正文、
分类名、计量单位这些都在库里,改代码不会跟。

新增两个可重跑的内容迁移脚本(都默认 dry-run、写库前自动备份、未覆盖的行只列不改):

· scripts/translate_content_ja.py + content_ja.json
  分类 10 条、轮播 3 条(标题/描述/按钮)、公告、活动 2 场(含奖品「たばこ10パック」)、
  资讯 6 篇(标题/摘要/正文全译);品牌名 64 条去掉中文段
  (「AmericanSpirit/美国精神」→「AmericanSpirit」)。

· scripts/fix_product_desc_unit.py
  products.unit 818 行:包→パック、个→個、盒→箱、套→セット、件→点;
  products.description 41 行(原本是把旧中文名复制了一份)按同一份
  「旧名→日文名」映射反查替换。

生产已执行:内容 44 处 + 品牌 64 条 + 单位 818 行 + 描述 41 行,逐项 dry-run 后写入。
2026-12-02 00:15:33 +08:00

200 lines
7.7 KiB
Python
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.
#!/usr/bin/env python3
"""把库里的金额从人民币换算成日元(一次性迁移)。
背景:站点原本按人民币定价(商品 50/58/100 元这种量级),要改成日本客人的日元口径。
金额本身只是数值,代码里没有任何汇率逻辑 —— 所以要么改数据、要么改显示层。
这个脚本走「改数据」:整库乘一个汇率并取整到 1 日元,之后前端只需要把符号换掉。
用法
python3 migrate_prices_to_jpy.py --db /path/sale.db --rate 20.8 --dry-run
python3 migrate_prices_to_jpy.py --db /path/sale.db --rate 20.8 --yes
安全措施
· 默认 dry-run,只打印改动前后样例与命中行数,不写库
· 写库前自动把 .db(含 -wal/-shm)备份到同目录 *.bak-jpy-<时间戳>
· 幂等:库里 currency_code 已经是 JPY 就拒绝再乘一次(除非 --force)
· 只碰「钱」的列;费率(*_rate)、次数(credit_cost)、id 一律不动
· 整个迁移放在一个事务里,任何一步失败整体回滚
"""
import argparse
import datetime as dt
import os
import shutil
import sqlite3
import sys
# (表, 列) —— 只列真正表示金额的列。费率与次数刻意排除。
MONEY_COLUMNS = [
("products", "price"),
("products", "promo_price"),
("products", "member_price"),
("products", "cost_price"),
("products", "min_amount"),
("products", "max_amount"),
("inventory", "cost_price"),
("inventory", "ship_fee"),
("shipping_templates", "first_fee"),
("shipping_templates", "additional_fee"),
("shipping_templates", "free_amount"),
("orders", "subtotal"),
("orders", "shipping_fee"),
("orders", "service_fee"),
("orders", "channel_fee"),
("orders", "packaging_fee"),
("orders", "international_fee"),
("orders", "total_amount"),
("orders", "declared_value"),
("orders", "supplier_ship_fee"),
("orders", "refund_amount"),
("order_items", "price"),
("order_items", "cost_price"),
("order_items", "ship_fee"),
("categories", "min_amount"),
("categories", "max_amount"),
("payment_channels", "min_amount"),
("payment_channels", "max_amount"),
("supplier_settlements", "sale_amount"),
("supplier_settlements", "cost_amount"),
("supplier_settlements", "ship_amount"),
("supplier_settlements", "total_amount"),
("coupons", "value"),
("coupons", "min_amount"),
("user_coupons", "value"),
("user_coupons", "min_amount"),
]
# 金额型的 system_settings(费率类不在此列)
MONEY_SETTINGS = ["packaging_fee", "shipping_fee_first_weight", "shipping_fee_per_gram"]
NEW_SETTINGS = {
"currency_code": "JPY",
"currency_symbol": "¥",
"currency_decimals": "0",
}
def table_cols(con, table):
return [r[1] for r in con.execute(f'PRAGMA table_info("{table}")')]
def backup(db_path):
stamp = dt.datetime.now().strftime("%Y%m%d-%H%M%S")
made = []
for suffix in ("", "-wal", "-shm"):
src = db_path + suffix
if os.path.exists(src):
dst = f"{db_path}.bak-jpy-{stamp}{suffix}"
shutil.copy2(src, dst)
made.append(dst)
return made
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--db", required=True)
ap.add_argument("--rate", type=float, default=20.8, help="1 CNY = ? JPY(默认 20.8)")
ap.add_argument("--dry-run", action="store_true", default=False)
ap.add_argument("--yes", action="store_true", default=False)
ap.add_argument("--force", action="store_true", default=False)
args = ap.parse_args()
if not os.path.exists(args.db):
sys.exit(f"找不到库文件:{args.db}")
if not args.dry_run and not args.yes:
sys.exit("写库需要 --yes(先跑一次 --dry-run 看结果)")
con = sqlite3.connect(args.db, isolation_level=None)
con.execute("PRAGMA busy_timeout = 30000")
settings = dict(con.execute("SELECT `key`, value FROM system_settings").fetchall())
# 幂等判据用 currency_migrated_at(本脚本自己写的时间戳),不要用 currency_code:
# 应用启动时的 SeedCurrencyDefaults 也会写 currency_code=JPY,
# 拿它当「已迁移」标志会让脚本在真正迁移之前就自我拒绝。
if settings.get("currency_migrated_at") and not args.force:
sys.exit(f"已迁移过(currency_migrated_at={settings['currency_migrated_at']}),不做第二次(重跑加 --force)")
plan = []
for table, col in MONEY_COLUMNS:
cols = table_cols(con, table)
if not cols or col not in cols:
continue
plan.append((table, col))
print(f"库:{args.db}")
print(f"汇率:1 CNY = {args.rate} JPY,结果取整到 1 日元")
print(f"命中 {len(plan)} 个金额列\n")
total_rows = 0
for table, col in plan:
rows = con.execute(
f'SELECT COUNT(*) FROM "{table}" WHERE "{col}" IS NOT NULL AND "{col}" <> 0'
).fetchone()[0]
total_rows += rows
sample = con.execute(
f'SELECT "{col}" FROM "{table}" WHERE "{col}" IS NOT NULL AND "{col}" <> 0 '
f'ORDER BY "{col}" DESC LIMIT 3'
).fetchall()
ex = ", ".join(f"{v[0]}→{round(v[0] * args.rate)}" for v in sample)
print(f" {table}.{col:20} 非零 {rows:>6} 行 例:{ex or '-'}")
money_settings = {
k: v for k, v in settings.items() if k in MONEY_SETTINGS and v not in ("", "0", "0.0", "0.00")
}
print(f"\n 金额型设置:{money_settings or '(无)'}")
print(f"\n合计非零金额单元格 {total_rows} 个")
if args.dry_run:
print("\n[dry-run] 未写库。确认无误后加 --yes 执行。")
return
backups = backup(args.db)
print("\n已备份:" + ", ".join(os.path.basename(b) for b in backups))
con.execute("BEGIN IMMEDIATE")
try:
for table, col in plan:
# ROUND 到整数:日元最小单位是 1 円,不带小数
con.execute(
f'UPDATE "{table}" SET "{col}" = ROUND("{col}" * ?, 0) '
f'WHERE "{col}" IS NOT NULL',
(args.rate,),
)
for k in money_settings:
try:
con.execute(
"UPDATE system_settings SET value = ? WHERE `key` = ?",
(str(round(float(money_settings[k]) * args.rate)), k),
)
except ValueError:
pass
for k, v in NEW_SETTINGS.items():
exists = con.execute("SELECT 1 FROM system_settings WHERE `key` = ?", (k,)).fetchone()
if exists:
con.execute("UPDATE system_settings SET value = ?, updated_at = ? WHERE `key` = ?",
(v, dt.datetime.now().isoformat(" ", "seconds"), k))
else:
con.execute(
"INSERT INTO system_settings (`key`, value, updated_at) VALUES (?, ?, ?)",
(k, v, dt.datetime.now().isoformat(" ", "seconds")),
)
con.execute(
"INSERT INTO system_settings (`key`, value, updated_at) VALUES ('currency_migrated_at', ?, ?) "
"ON CONFLICT(`key`) DO UPDATE SET value = excluded.value",
(dt.datetime.now().isoformat(" ", "seconds"), dt.datetime.now().isoformat(" ", "seconds")),
)
con.execute("COMMIT")
except Exception as exc: # noqa: BLE001
con.execute("ROLLBACK")
print(f"失败已回滚:{exc}")
raise
print("\n迁移完成。抽查:")
for table, col in plan[:6]:
v = con.execute(f'SELECT "{col}" FROM "{table}" WHERE "{col}" IS NOT NULL ORDER BY "{col}" DESC LIMIT 3').fetchall()
print(f" {table}.{col:20} 现在:{[x[0] for x in v]}")
if __name__ == "__main__":
main()