service.py 4.46 KB
from __future__ import annotations

import logging
from datetime import timedelta
from typing import Optional

from sqlalchemy import func, text
from sqlalchemy.orm import Session

from app.infrastructure.time import china_now
from app.customer_info.model import CustomerGroupPhone


logger = logging.getLogger(__name__)


class CustomerInfoService:
    """客户号码与群组关系维护服务。"""

    def __init__(self, db: Session):
        self.db = db

    def sync_from_customer_groups(self) -> int:
        """从 wecom_customer_groups 同步群状态与客户名到 customer_group_phones,返回受影响行数。

        按 group_id 关联,使用 INSERT ... ON DUPLICATE KEY UPDATE 完成新增与更新。
        """
        now = china_now()

        # 新增 + 更新:group_status / customer_name 变化都能覆盖
        upserted = self.db.execute(
            text("""
                INSERT INTO customer_group_phones (customer_name, group_id, group_status, create_time, update_time)
                SELECT wcg.customer_name, wcg.group_id, wcg.group_status, :now, :now
                FROM wecom_customer_groups wcg
                WHERE wcg.is_deleted = 0 AND wcg.group_id IS NOT NULL
                ON DUPLICATE KEY UPDATE
                    group_status = VALUES(group_status),
                    customer_name = VALUES(customer_name),
                    update_time = VALUES(update_time)
            """),
            {"now": now},
        ).rowcount

        # 对账:源表已逻辑删除(is_deleted=1)或不存在的群,标记目标行为 deleted
        reconciled = self.db.execute(
            text("""
                UPDATE customer_group_phones cgp
                LEFT JOIN wecom_customer_groups wcg
                    ON wcg.group_id = cgp.group_id AND wcg.is_deleted = 0 AND wcg.group_id IS NOT NULL
                SET cgp.group_status = 'deleted', cgp.update_time = :now
                WHERE wcg.group_id IS NULL AND cgp.group_status != 'deleted'
            """),
            {"now": now},
        ).rowcount

        self.db.commit()
        affected = upserted + reconciled
        logger.info("同步完成: upserted=%s reconciled=%s total=%s", upserted, reconciled, affected)
        return affected

    def bind_phone(self, group_id: str, phone: str) -> Optional[CustomerGroupPhone]:
        """用户填写手机号。"""
        record = (
            self.db.query(CustomerGroupPhone)
            .filter(CustomerGroupPhone.group_id == group_id)
            .first()
        )
        if not record:
            logger.warning("未找到匹配记录: group_id=%s", group_id)
            return None
        record.phone = phone
        self.db.commit()
        self.db.refresh(record)
        logger.info("手机号绑定成功: group_id=%s", group_id)
        return record

    def get_phone(self, group_id: str) -> Optional[CustomerGroupPhone]:
        """查询群绑定的手机号。"""
        return (
            self.db.query(CustomerGroupPhone)
            .filter(CustomerGroupPhone.group_id == group_id)
            .first()
        )

    def get_push_candidates(self, mode: str = "sync") -> list[CustomerGroupPhone]:
        """获取需要推送的记录。

        mode='sync': 同步触发推送, 仅 last_pushed_at IS NULL 的新记录。
        mode='daily': 每日推送, 仅推送创建时间在近 3 天内的记录(t, t+1, t+2),
                      且从未推送或上次推送日期非今日。
        """
        now = china_now()
        today = now.date()

        base_query = self.db.query(CustomerGroupPhone).filter(
            CustomerGroupPhone.phone.is_(None),
            CustomerGroupPhone.group_status == "active",
        )

        if mode == "sync":
            candidates = base_query.filter(CustomerGroupPhone.last_pushed_at.is_(None)).all()
        elif mode == "daily":
            window_start = today - timedelta(days=2)
            candidates = base_query.filter(
                (
                    (CustomerGroupPhone.last_pushed_at.is_(None))
                    | (func.date(CustomerGroupPhone.last_pushed_at) < today)
                ),
                func.date(CustomerGroupPhone.create_time).between(window_start, today),
            ).all()
        else:
            raise ValueError(f"Unknown push mode: {mode}")

        return candidates

    def mark_pushed(self, record: CustomerGroupPhone) -> None:
        """推送成功后设置 last_pushed_at。"""
        record.last_pushed_at = china_now()
        self.db.commit()