309 lines
13 KiB
Python
309 lines
13 KiB
Python
"""Register-quote flow: entities → draft → resolve → review (+missing) → commit."""
|
|
import logging
|
|
|
|
from app import drafts as draft_store
|
|
from app.api.client import ApiError
|
|
from app.drafts import (
|
|
KIND_QUOTE, build_quote_request, compute_quote_missing, merge_quote_patch,
|
|
new_quote_payload, quote_ready,
|
|
)
|
|
from app.keyboards import quote_review_keyboard
|
|
from app.resolve import safe_resolve
|
|
from app.texts import ERR_GENERIC, quote_committed_report, quote_review_text, esc
|
|
|
|
logger = logging.getLogger("bot.quote")
|
|
|
|
FIELD_FA = {"sup": "تأمینکننده", "prj": "پروژه"}
|
|
|
|
|
|
async def handle_entities(
|
|
ctx, chat_id, user, patch: dict, source: str | None,
|
|
incoming_msg_id: int | None = None,
|
|
target_draft = None,
|
|
) -> None:
|
|
prev_review_msg_id = None
|
|
if target_draft is not None:
|
|
draft = target_draft
|
|
prev_review_msg_id = draft.review_message_id
|
|
payload = draft.payload
|
|
merge_quote_patch(payload, patch)
|
|
draft.source_message_id = incoming_msg_id
|
|
else:
|
|
payload = new_quote_payload()
|
|
merge_quote_patch(payload, patch)
|
|
draft = await draft_store.create(
|
|
chat_id, KIND_QUOTE, payload, source=source, source_message_id=incoming_msg_id
|
|
)
|
|
|
|
await resolve_payload(ctx, payload)
|
|
await draft_store.save_payload(
|
|
draft,
|
|
missing={"fields": compute_quote_missing(payload)},
|
|
source_message_id=incoming_msg_id,
|
|
)
|
|
|
|
if prev_review_msg_id:
|
|
try:
|
|
await ctx.delete(chat_id, prev_review_msg_id)
|
|
except Exception as e:
|
|
logger.warning("Could not delete previous review message %s: %s", prev_review_msg_id, e)
|
|
|
|
await render(ctx, chat_id, draft, fresh=True, reply_to=incoming_msg_id)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# resolution
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def resolve_payload(ctx, payload: dict) -> None:
|
|
options = payload.setdefault("options", {})
|
|
|
|
if not payload.get("supplier_id") and payload.get("supplier_name"):
|
|
res = await safe_resolve(ctx.resolver, "supplier", payload["supplier_name"])
|
|
if res.resolved:
|
|
payload["supplier_id"] = res.candidates[0].id
|
|
payload["supplier_name"] = res.candidates[0].name
|
|
options.pop("sup", None)
|
|
elif res.candidates:
|
|
options["sup"] = [{"id": c.id, "name": c.name} for c in res.candidates]
|
|
else:
|
|
options.pop("sup", None)
|
|
|
|
if not payload.get("project_id") and payload.get("project_name"):
|
|
res = await safe_resolve(ctx.resolver, "project", payload["project_name"])
|
|
if res.resolved:
|
|
payload["project_id"] = res.candidates[0].id
|
|
payload["project_name"] = res.candidates[0].name
|
|
if payload["project_id"] not in payload.get("project_ids", []):
|
|
payload.setdefault("project_ids", []).append(payload["project_id"])
|
|
options.pop("prj", None)
|
|
elif res.candidates:
|
|
options["prj"] = [{"id": c.id, "name": c.name} for c in res.candidates]
|
|
else:
|
|
options.pop("prj", None)
|
|
|
|
for p_name in payload.get("project_names") or []:
|
|
res = await safe_resolve(ctx.resolver, "project", p_name)
|
|
if res.resolved:
|
|
p_id = res.candidates[0].id
|
|
if p_id not in payload.get("project_ids", []):
|
|
payload.setdefault("project_ids", []).append(p_id)
|
|
if not payload.get("project_id"):
|
|
payload["project_id"] = p_id
|
|
|
|
for i, item in enumerate(payload.get("items") or [], start=1):
|
|
if not item.get("material_id") and item.get("material_name"):
|
|
res = await safe_resolve(ctx.resolver, "material", item["material_name"])
|
|
if res.resolved:
|
|
_set_material(item, res.candidates[0].id, res.candidates[0].name, res.candidates[0].extra)
|
|
options.pop(f"mat{i}", None)
|
|
elif res.candidates:
|
|
options[f"mat{i}"] = [{"id": c.id, "name": c.name} for c in res.candidates]
|
|
else:
|
|
options.pop(f"mat{i}", None)
|
|
if not item.get("unit_id"):
|
|
await _resolve_unit(ctx, item)
|
|
|
|
|
|
def _set_material(item: dict, material_id: str, name: str, extra: dict | None = None) -> None:
|
|
item["material_id"] = material_id
|
|
item["material_row"] = {"id": material_id, "canonical_unit_id": (extra or {}).get("canonical_unit_id")}
|
|
|
|
|
|
async def _resolve_unit(ctx, item: dict) -> None:
|
|
if item.get("unit_id"):
|
|
return
|
|
if item.get("unit_name"):
|
|
res = await safe_resolve(ctx.resolver, "unit", item["unit_name"])
|
|
if res.resolved:
|
|
item["unit_id"] = res.candidates[0].id
|
|
item["unit_explicit"] = True
|
|
item["unit_name"] = res.candidates[0].name
|
|
return
|
|
canonical = ((item.get("material_row") or {}).get("canonical_unit_id"))
|
|
if canonical:
|
|
item["unit_id"] = str(canonical)
|
|
item["unit_explicit"] = False
|
|
|
|
|
|
async def apply_pick(ctx, chat_id, user, draft, field: str, choice: dict) -> None:
|
|
payload = draft.payload
|
|
options = payload.setdefault("options", {})
|
|
options.pop(field, None)
|
|
|
|
if field == "sup":
|
|
payload["supplier_id"] = choice["id"]
|
|
payload["supplier_name"] = choice["name"]
|
|
elif field == "prj":
|
|
payload["project_id"] = choice["id"]
|
|
payload["project_name"] = choice["name"]
|
|
elif field.startswith("mat"):
|
|
index = int(field[3:]) - 1
|
|
items = payload.get("items") or []
|
|
if 0 <= index < len(items):
|
|
items[index]["material_name"] = choice["name"]
|
|
_set_material(items[index], choice["id"], choice["name"])
|
|
await _resolve_unit(ctx, items[index])
|
|
elif field.startswith("unit"):
|
|
index = int(field[4:]) - 1
|
|
items = payload.get("items") or []
|
|
if 0 <= index < len(items):
|
|
items[index]["unit_id"] = choice["id"]
|
|
items[index]["unit_explicit"] = True
|
|
items[index]["unit_name"] = choice["name"]
|
|
|
|
await resolve_payload(ctx, payload)
|
|
await draft_store.save_payload(draft, missing={"fields": compute_quote_missing(payload)})
|
|
await render(ctx, chat_id, draft, fresh=False)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# rendering
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _pick_rows(payload: dict) -> list[list[str]]:
|
|
"""Field labels shown as pick-button rows (via keyboards.pick_buttons)."""
|
|
rows: list[list[str]] = []
|
|
options = payload.get("options") or {}
|
|
if options.get("sup"):
|
|
rows.append(["sup"] + [o["name"] for o in options["sup"]])
|
|
if options.get("prj"):
|
|
rows.append(["prj"] + [o["name"] for o in options["prj"]])
|
|
for i, item in enumerate(payload.get("items") or [], start=1):
|
|
if options.get(f"mat{i}"):
|
|
rows.append([f"mat{i}"] + [o["name"] for o in options[f"mat{i}"]])
|
|
if options.get(f"unit{i}"):
|
|
rows.append([f"unit{i}"] + [o["name"] for o in options[f"unit{i}"]])
|
|
return rows
|
|
|
|
|
|
def _keyboard(payload: dict, draft_id: str, wizard_url: str | None = None) -> dict:
|
|
from app.keyboards import pick_buttons
|
|
|
|
prefix = str(draft_id)[:8]
|
|
pick_rows: list[list[dict]] = []
|
|
for row in _pick_rows(payload):
|
|
field, names = row[0], row[1:]
|
|
pick_rows += pick_buttons(prefix, field, names[:6])
|
|
ready_items = sum(
|
|
1 for it in payload.get("items") or []
|
|
if it.get("material_id") and it.get("quantity") and it.get("unit_id")
|
|
)
|
|
has_partial = 0 < ready_items < len(payload.get("items") or [])
|
|
return quote_review_keyboard(prefix, pick_rows, has_partial_option=has_partial, wizard_url=wizard_url)
|
|
|
|
|
|
async def render(ctx, chat_id, draft, fresh: bool = True, note: str | None = None,
|
|
reply_to: int | None = None) -> None:
|
|
from app.config import settings
|
|
|
|
payload = draft.payload
|
|
missing = compute_quote_missing(payload)
|
|
wizard_url = f"{settings.FRONTEND_URL}/wizard?draft={draft.id}"
|
|
text = quote_review_text(payload, missing, status_note=note)
|
|
text += f"\n\n🖥 مشاهده و تکمیل در ویزارد:\n{wizard_url}"
|
|
keyboard = _keyboard(payload, str(draft.id), wizard_url=wizard_url)
|
|
if fresh:
|
|
message = await ctx.send(chat_id, text, reply_markup=keyboard, reply_to=reply_to)
|
|
new_review_id = (message or {}).get("message_id")
|
|
if new_review_id:
|
|
draft.review_message_id = new_review_id
|
|
await draft_store.save_payload(
|
|
draft,
|
|
missing={"fields": missing},
|
|
review_message_id=new_review_id,
|
|
source_message_id=reply_to or draft.source_message_id,
|
|
)
|
|
await draft_store.set_bale_updated_at(draft.id)
|
|
else:
|
|
await ctx.edit(chat_id, draft.review_message_id, text, reply_markup=keyboard)
|
|
await draft_store.save_payload(draft, missing={"fields": missing})
|
|
await draft_store.set_bale_updated_at(draft.id)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# commit
|
|
# ---------------------------------------------------------------------------
|
|
|
|
async def commit(ctx, chat_id, user, draft, only_resolved: bool = False) -> None:
|
|
payload = draft.payload
|
|
await resolve_payload(ctx, payload)
|
|
|
|
# 1. Sequential pre-creation for new supplier if user wants to commit
|
|
if not payload.get("supplier_id") and payload.get("supplier_name"):
|
|
cat_id = payload.get("supplier_category_id")
|
|
if not cat_id:
|
|
cats = await ctx.resolver.categories()
|
|
if cats:
|
|
cat_id = cats[0].id
|
|
if cat_id:
|
|
try:
|
|
sup_body = {
|
|
"name": payload["supplier_name"],
|
|
"category_id": cat_id,
|
|
}
|
|
if payload.get("supplier_phone"):
|
|
sup_body["phone"] = payload["supplier_phone"]
|
|
created_sup = await ctx.api.create_supplier(sup_body, actor_id=user.actor_id)
|
|
payload["supplier_id"] = created_sup["id"]
|
|
ctx.resolver.invalidate("suppliers")
|
|
except Exception as e:
|
|
logger.warning("Could not auto-create supplier: %s", e)
|
|
|
|
# 2. Sequential pre-creation for new materials
|
|
for i, item in enumerate(payload.get("items") or [], start=1):
|
|
if not item.get("material_id") and item.get("material_name") and item.get("unit_id"):
|
|
try:
|
|
created_mat = await ctx.api.create_material({
|
|
"name": item["material_name"],
|
|
"canonical_unit_id": int(item["unit_id"]),
|
|
}, actor_id=user.actor_id)
|
|
_set_material(item, created_mat["id"], created_mat.get("name") or item["material_name"])
|
|
ctx.resolver.invalidate("materials")
|
|
except Exception as e:
|
|
logger.warning("Could not auto-create material: %s", e)
|
|
|
|
ready, blockers = quote_ready(payload)
|
|
body, problems = build_quote_request(payload, only_resolved_items=only_resolved)
|
|
if body is None:
|
|
lines = ["ثبت ممکن نیست؛ اینها را اول مشخص کن:"] + [f"❌ {esc(p)}" for p in problems]
|
|
await ctx.send(chat_id, "\n".join(lines))
|
|
return
|
|
if not ready and not only_resolved:
|
|
lines = ["برای ثبت کامل، اول اینها را مشخص کن:"] + [f"❌ {esc(b)}" for b in blockers]
|
|
lines += ["", "یا دکمه «ثبت فقط اقلام مشخص» را بزن."]
|
|
await ctx.send(chat_id, "\n".join(lines))
|
|
return
|
|
|
|
try:
|
|
created = await ctx.api.create_quote(body, actor_id=user.actor_id)
|
|
except ApiError as exc:
|
|
await ctx.send(chat_id, ERR_GENERIC.format(detail=esc(exc.message)))
|
|
return
|
|
except Exception:
|
|
logger.exception("create_quote failed")
|
|
await ctx.send(chat_id, ERR_GENERIC.format(detail="خطای شبکه"))
|
|
return
|
|
|
|
await draft_store.set_status(draft.id, "committed")
|
|
ctx.pending.pop(chat_id, None)
|
|
ctx.resolver.invalidate()
|
|
|
|
if draft.review_message_id:
|
|
try:
|
|
quote_id = (created or {}).get("id") or ""
|
|
msg = f"✅ این پیشنهاد در سیستم با موفقیت ثبت نهایی شد.\nشناسه پیشنهاد: {quote_id}"
|
|
await ctx.edit(chat_id, draft.review_message_id, msg, reply_markup=None)
|
|
await draft_store.set_bale_updated_at(draft.id)
|
|
except Exception:
|
|
pass
|
|
|
|
remaining = [
|
|
m["label"] for m in compute_quote_missing(payload)
|
|
if not m["blocking"] and not m["ok"]
|
|
]
|
|
dropped = len(payload.get("items") or []) - len(body.get("line_items") or [])
|
|
if dropped > 0:
|
|
remaining.append(f"{dropped} قلم ناشناس حذف شد")
|
|
await ctx.send(chat_id, quote_committed_report(created, payload, remaining))
|