feat: полнота извлечения — ресурсные индексы/машинисты, структура стоимости, сметная цена КА
Ре-аудит покрытия .gge: добавлено что выбрасывалось — индекс пересчёта ресурсов с обоснованием, детали машинистов, структура стоимости расценки (машины/материалы/ зарплата), comment позиции, накладные/прибыль в рублях, возвратные материалы. Фикс Transport (цена из PricePerUnitCur, была 0). КА: сметная цена EstimateWithoutVAT (идёт в смету, ≠ рыночная) + склад + перевозка. Все парсеры сведены в gge_deep (parse_ka перенесён из build-скрипта), убраны дубли хелперов. Добавлены юнит-тесты парсеров (tests/test_gge_deep.py, 4/4). verify_corpus exit 0, обезличивание чисто (email/телефон/ИНН = 0). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+107
-28
@@ -41,12 +41,40 @@ def _f(s: str) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def _index(node) -> dict | None:
|
||||
"""Индекс пересчёта ресурса база→текущий с обоснованием (Index/Reason)."""
|
||||
idx = node.find("Index")
|
||||
if idx is None:
|
||||
return None
|
||||
val = _f(_t(idx, "Value/IndexValue")) or _f(_t(idx, "Value/Final"))
|
||||
reason = _t(idx, "Reason")
|
||||
if not val and not reason:
|
||||
return None
|
||||
return {"value": val, "reason": reason}
|
||||
|
||||
|
||||
def _material(mat, external=False) -> dict:
|
||||
d = {
|
||||
"code": _t(mat, "Code"),
|
||||
"name": _t(mat, "Name"),
|
||||
"consumption": _f(_t(mat, "Consumption")),
|
||||
"unit": _t(mat, "Unit"),
|
||||
"price_base": _f(_t(mat, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(mat, "PricePerUnitCur")),
|
||||
"index": _index(mat),
|
||||
}
|
||||
if external:
|
||||
d["external"] = True
|
||||
return d
|
||||
|
||||
|
||||
def _resources(cost) -> dict:
|
||||
"""Ресурсный состав расценки (нормы на единицу): рабочие/машины/материалы."""
|
||||
"""Ресурсный состав расценки (нормы на единицу): рабочие/машины/материалы,
|
||||
с индексами пересчёта и деталями машинистов."""
|
||||
out = {"workers": [], "machines": [], "materials": []}
|
||||
ri = cost.find("ResourcesInternal")
|
||||
if ri is None:
|
||||
return out
|
||||
ri = ET.Element("empty")
|
||||
for w in ri.findall("Worker"):
|
||||
out["workers"].append({
|
||||
"name": (_t(w, "Name") or "").strip(),
|
||||
@@ -55,6 +83,7 @@ def _resources(cost) -> dict:
|
||||
"price_cur": _f(_t(w, "PricePerUnitCur")),
|
||||
})
|
||||
for m in ri.findall("Machine"):
|
||||
mach = m.find("Machinist")
|
||||
out["machines"].append({
|
||||
"code": _t(m, "Code"),
|
||||
"name": _t(m, "Name"),
|
||||
@@ -62,30 +91,20 @@ def _resources(cost) -> dict:
|
||||
"unit": _t(m, "Unit"),
|
||||
"price_base": _f(_t(m, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(m, "PricePerUnitCur")),
|
||||
"machinist_grade": _t(m, "Machinist/Grade"),
|
||||
"index": _index(m),
|
||||
"machinist": {
|
||||
"consumption": _f(_t(mach, "Consumption")),
|
||||
"price_cur": _f(_t(mach, "PricePerUnitCur")),
|
||||
"grade": _t(mach, "Grade"),
|
||||
} if mach is not None else None,
|
||||
})
|
||||
for mat in ri.findall("Material"):
|
||||
out["materials"].append({
|
||||
"code": _t(mat, "Code"),
|
||||
"name": _t(mat, "Name"),
|
||||
"consumption": _f(_t(mat, "Consumption")),
|
||||
"unit": _t(mat, "Unit"),
|
||||
"price_base": _f(_t(mat, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(mat, "PricePerUnitCur")),
|
||||
})
|
||||
out["materials"].append(_material(mat))
|
||||
# Внешние ресурсы (оборудование/неучтённые материалы из Cost/Resources)
|
||||
ext = cost.find("Resources")
|
||||
if ext is not None:
|
||||
for mat in ext.findall("Material"):
|
||||
out["materials"].append({
|
||||
"code": _t(mat, "Code"),
|
||||
"name": _t(mat, "Name"),
|
||||
"consumption": _f(_t(mat, "Consumption")),
|
||||
"unit": _t(mat, "Unit"),
|
||||
"price_base": _f(_t(mat, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(mat, "PricePerUnitCur")),
|
||||
"external": True,
|
||||
})
|
||||
out["materials"].append(_material(mat, external=True))
|
||||
return out
|
||||
|
||||
|
||||
@@ -137,19 +156,23 @@ def parse_estimate_full(path: Path) -> dict:
|
||||
"name": (_t(dm, "Name") or "").strip(),
|
||||
"unit": _t(dm, "Unit"),
|
||||
"consumption": _f(_t(dm, "ConsumptionTotal")) or _f(_t(dm, "Consumption")),
|
||||
"price_base": _f(_t(dm, "PricePerUnitBase")),
|
||||
"price_cur": _f(_t(dm, "PricePerUnitCur")),
|
||||
"comment": _t(dm, "Comment"),
|
||||
"is_return": _t(dm, "IsReturnMat").lower() == "true",
|
||||
})
|
||||
# Перевозочная позиция (Transport — доставка грузов)
|
||||
# Перевозочная позиция (Transport — доставка грузов).
|
||||
# Цена в PricePerUnitCur (у Transport нет Totals/Current/Direct).
|
||||
tr = it.find("Transport")
|
||||
if tr is not None and _t(tr, "Name"):
|
||||
qty = _f(_t(tr, "QuantityTotal")) or _f(_t(tr, "Quantity"))
|
||||
direct = _f(_t(tr, "Totals/Current/Direct")) or _f(_t(tr, "PriceTotalCur"))
|
||||
positions.append({
|
||||
"code": _t(tr, "Code"), "name": (_t(tr, "Name") or "").strip(),
|
||||
"prefix": _t(tr, "Prefix"), "unit": _t(tr, "Unit"),
|
||||
"quantity": qty,
|
||||
"quantity": qty, "comment": _t(tr, "Comment"),
|
||||
"labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"unit_cost_cur": round(direct / qty, 2) if qty else 0.0,
|
||||
"unit_cost_cur": _f(_t(tr, "PricePerUnitCur")),
|
||||
"cost_structure": None,
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
"kind": "transport",
|
||||
@@ -159,8 +182,15 @@ def parse_estimate_full(path: Path) -> dict:
|
||||
if not name:
|
||||
continue
|
||||
qty_total = _f(_t(cost, "QuantityTotal")) or _f(_t(cost, "Quantity"))
|
||||
direct_cur = _f(_t(cost, "Totals/Current/Direct"))
|
||||
tc = cost.find("Totals/Current")
|
||||
direct_cur = _f(_t(tc, "Direct")) if tc is not None else 0.0
|
||||
unit_cost_cur = round(direct_cur / qty_total, 2) if qty_total else 0.0
|
||||
# Структура стоимости расценки: сколько на машины/материалы/зарплату
|
||||
cost_structure = {
|
||||
"machines": _f(_t(tc, "Machines")), "materials": _f(_t(tc, "Materials")),
|
||||
"salary": _f(_t(tc, "Salary")), "machinist_salary": _f(_t(tc, "MachinistSalary")),
|
||||
"workers_salary": _f(_t(tc, "WorkersSalary")),
|
||||
} if tc is not None else None
|
||||
ov = it.find("Overheads")
|
||||
pr = it.find("Profits")
|
||||
positions.append({
|
||||
@@ -169,13 +199,17 @@ def parse_estimate_full(path: Path) -> dict:
|
||||
"prefix": _t(cost, "Prefix"),
|
||||
"unit": _t(cost, "Unit"),
|
||||
"quantity": qty_total,
|
||||
"comment": _t(cost, "Comment"),
|
||||
"labor_ch": _f(_t(cost, "PerUnit/LaborCosts")),
|
||||
"machinist_ch": _f(_t(cost, "PerUnit/MachinistLaborCosts")),
|
||||
"unit_cost_cur": unit_cost_cur,
|
||||
"cost_structure": cost_structure,
|
||||
"overhead": {"value": _t(ov, "Value"), "target": _t(ov, "Target"),
|
||||
"reason": _t(ov, "Reason")} if ov is not None else None,
|
||||
"reason": _t(ov, "Reason"), "price_cur": _f(_t(ov, "PriceCur"))}
|
||||
if ov is not None else None,
|
||||
"profit": {"value": _t(pr, "Value"), "target": _t(pr, "Target"),
|
||||
"reason": _t(pr, "Reason")} if pr is not None else None,
|
||||
"reason": _t(pr, "Reason"), "price_cur": _f(_t(pr, "PriceCur"))}
|
||||
if pr is not None else None,
|
||||
"coefficients": _coefficients(cost),
|
||||
"resources": _resources(cost),
|
||||
"kind": "cost",
|
||||
@@ -208,6 +242,7 @@ def parse_vor(path: Path) -> dict:
|
||||
continue
|
||||
link = w.find(".//Link")
|
||||
source = _t(link, "PageDescription") if link is not None else ""
|
||||
page = _t(link, "PageNumber") if link is not None else ""
|
||||
works.append({
|
||||
"section": sec_name,
|
||||
"name": name,
|
||||
@@ -215,10 +250,54 @@ def parse_vor(path: Path) -> dict:
|
||||
"quantity": _f(_t(w, "Quantity")),
|
||||
"formula": _t(w, "QuantityFormula"),
|
||||
"comment": _t(w, "Comment"),
|
||||
"source": source,
|
||||
"source": (f"{source} л.{page}" if page else source).strip(),
|
||||
})
|
||||
return {
|
||||
"num": _t(root, "Num"),
|
||||
"reason": _t(root, "Reason"),
|
||||
"works": works,
|
||||
}
|
||||
|
||||
|
||||
def parse_ka(data: bytes) -> list[dict]:
|
||||
"""Разбор КА (MarketAnalysis): материал → офферы поставщиков с ценами.
|
||||
|
||||
Возвращает RAW (обезличивание — на стороне индексатора). Per оффер:
|
||||
market_price (цена оффера без НДС), estimate_price (СМЕТНАЯ цена, идёт в
|
||||
смету), price_vat (с НДС), storage/transport (заготовит.-складские/перевозка),
|
||||
delivery (условия), region, period, winner, реквизиты поставщика (для
|
||||
обезличивания индексатором).
|
||||
"""
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError:
|
||||
return []
|
||||
items = []
|
||||
for item in root.iter("Item"):
|
||||
name = (_t(item, "Name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
offers = []
|
||||
for n, off in enumerate(item.findall("Offer"), 1):
|
||||
op = off.find("OfferPrice")
|
||||
market = _f(_t(off, "OfferPrice/OfferUnitWithoutVAT")) \
|
||||
or _f(_t(off, "OfferPrice/OfferWithoutVAT"))
|
||||
if market <= 0:
|
||||
continue
|
||||
offers.append({
|
||||
"vendor": f"Поставщик {n}", # позиционно; реквизиты не извлекаем
|
||||
"market_price": round(market, 2),
|
||||
"estimate_price": round(_f(_t(op, "EstimateWithoutVAT")), 2) if op is not None else 0.0,
|
||||
"price_vat": round(_f(_t(off, "OfferPrice/OfferWithVAT")), 2) or None,
|
||||
"storage": _f(_t(off, "Storage/Price")) or None,
|
||||
"transport": _f(_t(off, "Transportation/Price")) or None,
|
||||
"delivery": _t(off, "OfferPrice/DeliveryTerms"),
|
||||
"region": _t(off, "Region/Name"),
|
||||
"period": f"{_t(off, 'OfferDate/Year')} Q{_t(off, 'OfferDate/Quarter')}".strip(),
|
||||
"country": _t(off, "OriginCountry"),
|
||||
"winner": _t(off, "Winner").lower() == "true",
|
||||
})
|
||||
if offers:
|
||||
items.append({"name": name, "unit": _t(item, "Unit"),
|
||||
"type": _t(item, "Type"), "offers": offers})
|
||||
return items
|
||||
|
||||
Reference in New Issue
Block a user