#!/bin/bash
# 每日ERP数据同步 — 凌晨3点执行
# 由Hermes cron调度
# P1扩展: 增加CRM模块和产模块同步
source /root/cma-management/backend/venv/bin/activate
cd /root/cma-management/backend

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}

log "=" 60
log "ERP每日同步开始"
log "=" 60

# 1. 总账模块同步（原有）
log "--- 总账模块同步 ---"
python3 -c "
from scripts.erp_sync import run_sync
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
run_sync(dry_run=False, use_api=False)
" >> /root/cma-management/backend/logs/erp_sync_daily.log 2>&1

# 2. CRM模块同步（P1新增）
log "--- CRM模块同步 ---"
python3 -c "
from scripts.erp_sync import run_sync
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
run_sync(dry_run=False, kpi_codes=['C_RETENTION_RATE', 'C_NEW_CLIENTS'], use_api=False)
" >> /root/cma-management/backend/logs/erp_sync_crm.log 2>&1

# 3. 生产模块同步（P1新增）
log "--- 生产模块同步 ---"
python3 -c "
from scripts.erp_sync import run_sync
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
run_sync(dry_run=False, kpi_codes=['F_QUALITY_RATE', 'F_REWORK_RATE'], use_api=False)
" >> /root/cma-management/backend/logs/erp_sync_production.log 2>&1

log "=" 60
log "ERP每日同步完成"
log "=" 60
