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:
@@ -8,9 +8,9 @@
|
||||
|
||||
| Файл | Что | Источник |
|
||||
|------|-----|----------|
|
||||
| `estimates_index.json` (~10 МБ) | 3097 расценок с ПОЛНЫМ составом: работа→код ГЭСН→ед→**ресурсы (рабочие/машины/материалы с нормами и ценами)**→цена/ед→трудозатраты→накладные/прибыль (с обоснованием)→коэффициенты→freq→объём. + 6796 прямых материалов с ценами | 2519 `.gge` ЛСР/ОСР (67 256 позиций) |
|
||||
| `ka_index.json` (~3.7 МБ) | 3922 материала: цена min/median/max/**winner**→обезличенные офферы→регион→квартал | 181 zip КА (4587 позиций) |
|
||||
| `vor_index.json` (~8 МБ) | 25 834 работы: ед→объём (min/median/max)→**формула расчёта**→ссылка на лист обоснования | 1951 `.gge` ВОР, схема QuantityTakeoff |
|
||||
| `estimates_index.json` (~11 МБ) | 3097 расценок с ПОЛНЫМ составом: работа→код ГЭСН→ед→**ресурсы** (рабочие/машины/материалы + нормы + цены база/тек + **индекс пересчёта с обоснованием** + машинисты)→цена/ед→**структура стоимости** (машины/материалы/зарплата)→трудозатраты→накладные/прибыль (с обоснованием+руб)→коэффициенты→comment→Transport-позиции→freq→объём. + 6796 прямых материалов (цена, возвратный-флаг) | 2519 `.gge` ЛСР/ОСР (67 256 позиций) |
|
||||
| `ka_index.json` (~5.3 МБ) | 3922 материала: **сметная цена** (EstimateWithoutVAT) min/median/max/**winner** + рыночная + склад + перевозка→обезличенные офферы→регион→квартал | 181 zip КА |
|
||||
| `vor_index.json` (~8.5 МБ) | 25 834 работы: ед→объём (min/median/max)→**формула расчёта**→ссылка на лист (с номером) | 1951 `.gge` ВОР, схема QuantityTakeoff |
|
||||
|
||||
## Поиск (3 MCP-tool + glm-tool)
|
||||
|
||||
@@ -25,10 +25,9 @@
|
||||
|
||||
## Парсинг
|
||||
|
||||
`gge_deep.py` — глубокий разбор всех схем:
|
||||
- ЛСР/ОСР (`LocalEstimate`/`ObjectEstimate`) → состав, цены база/текущие, накладные, коэффициенты
|
||||
- ВОР (`QuantityTakeoff`) → работа→объём→формула→источник
|
||||
- КА (`MarketAnalysis`) парсится в `scripts/build_ka_index.py`
|
||||
`gge_deep.py` — глубокий разбор ВСЕХ схем (один модуль): `parse_estimate_full`
|
||||
(ЛСР/ОСР), `parse_vor` (QuantityTakeoff), `parse_ka` (MarketAnalysis). Юнит-тесты
|
||||
на синтетических фикстурах: `tests/test_gge_deep.py` (4/4, без SSD).
|
||||
|
||||
## Пересборка / проверка
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+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
|
||||
|
||||
+3
-2
@@ -128,8 +128,9 @@ def find_in_real_estimates(query: str, top_k: int = 5) -> list[dict]:
|
||||
results.append((score, it["freq"], it))
|
||||
results.sort(key=lambda x: (x[0], x[1]), reverse=True)
|
||||
keys = ("code", "name", "unit", "prefix", "kind", "freq", "norm_sets", "regions",
|
||||
"qty", "unit_cost_cur", "labor_ch", "machinist_ch", "price_base",
|
||||
"price_cur", "overhead", "profit", "coefficients", "resources", "examples")
|
||||
"qty", "comment", "unit_cost_cur", "cost_structure", "labor_ch",
|
||||
"machinist_ch", "price_base", "price_cur", "overhead", "profit",
|
||||
"coefficients", "resources", "examples")
|
||||
return [{k: it.get(k) for k in keys} for _, _, it in results[:top_k]]
|
||||
|
||||
|
||||
|
||||
+10
-54
@@ -22,66 +22,19 @@ import json
|
||||
import statistics
|
||||
import sys
|
||||
import zipfile
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from gge_tools import _decode_zip_name # noqa: E402
|
||||
from gge_deep import scrub # noqa: E402 единый обезличиватель (960-06, пикеты, имя проекта)
|
||||
from gge_deep import parse_ka, scrub # noqa: E402 общий парсер + обезличиватель
|
||||
|
||||
MAX_OFFERS = 8 # храним до 8 офферов на материал (показать разброс)
|
||||
|
||||
|
||||
def _txt(el, path: str) -> str:
|
||||
node = el.find(path)
|
||||
return (node.text or "").strip() if node is not None and node.text else ""
|
||||
|
||||
|
||||
def _fnum(s: str) -> float:
|
||||
try:
|
||||
return float(s)
|
||||
except (ValueError, TypeError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_ka_gge(data: bytes) -> list[dict]:
|
||||
"""Разобрать КА .gge → список материалов с обезличенными офферами."""
|
||||
try:
|
||||
root = ET.fromstring(data)
|
||||
except ET.ParseError:
|
||||
return []
|
||||
items = []
|
||||
for item in root.iter("Item"):
|
||||
name = scrub(_txt(item, "Name"))
|
||||
if not name:
|
||||
continue
|
||||
unit = _txt(item, "Unit")
|
||||
mtype = _txt(item, "Type")
|
||||
offers = []
|
||||
for n, off in enumerate(item.findall("Offer"), 1):
|
||||
price_unit = _fnum(_txt(off, "OfferPrice/OfferUnitWithoutVAT")) \
|
||||
or _fnum(_txt(off, "OfferPrice/OfferWithoutVAT"))
|
||||
price_vat = _fnum(_txt(off, "OfferPrice/OfferWithVAT"))
|
||||
region = _txt(off, "Region/Name")
|
||||
year = _txt(off, "OfferDate/Year")
|
||||
quarter = _txt(off, "OfferDate/Quarter")
|
||||
winner = _txt(off, "Winner").lower() == "true"
|
||||
country = _txt(off, "OriginCountry")
|
||||
if price_unit <= 0:
|
||||
continue
|
||||
offers.append({
|
||||
"vendor": f"Поставщик {n}", # обезличено
|
||||
"price": round(price_unit, 2),
|
||||
"price_vat": round(price_vat, 2) if price_vat else None,
|
||||
"region": region,
|
||||
"period": f"{year} Q{quarter}" if year and quarter else year,
|
||||
"country": country,
|
||||
"winner": winner,
|
||||
})
|
||||
if offers:
|
||||
items.append({"name": name, "unit": unit, "type": mtype, "offers": offers})
|
||||
return items
|
||||
def _offer_price(o: dict) -> float:
|
||||
"""Цена для статистики: СМЕТНАЯ (идёт в смету), fallback — рыночная оффера."""
|
||||
return o.get("estimate_price") or o.get("market_price") or 0.0
|
||||
|
||||
|
||||
def build(price_dir: Path, out_dir: Path) -> dict:
|
||||
@@ -102,7 +55,10 @@ def build(price_dir: Path, out_dir: Path) -> dict:
|
||||
n_no_gge += 1
|
||||
continue
|
||||
for gi in gge_infos:
|
||||
for mat in _parse_ka_gge(z.read(gi)):
|
||||
for mat in parse_ka(z.read(gi)):
|
||||
mat["name"] = scrub(mat["name"])
|
||||
if not mat["name"]:
|
||||
continue
|
||||
n_items += 1
|
||||
key = mat["name"].lower()
|
||||
rec = agg.get(key)
|
||||
@@ -124,8 +80,8 @@ def build(price_dir: Path, out_dir: Path) -> dict:
|
||||
|
||||
items = []
|
||||
for rec in agg.values():
|
||||
prices = [o["price"] for o in rec["offers"] if o["price"] > 0]
|
||||
winner = next((o["price"] for o in rec["offers"] if o["winner"]), None)
|
||||
prices = [p for p in (_offer_price(o) for o in rec["offers"]) if p > 0]
|
||||
winner = next((_offer_price(o) for o in rec["offers"] if o["winner"]), None)
|
||||
pstat = {}
|
||||
if prices:
|
||||
pstat = {
|
||||
|
||||
@@ -75,7 +75,8 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"freq": 0, "_best_res": -1,
|
||||
# обогащённые поля (из самого полного вхождения)
|
||||
"unit_cost_cur": 0.0, "labor_ch": 0.0, "machinist_ch": 0.0,
|
||||
"price_base": "", "price_cur": "",
|
||||
"price_base": "", "price_cur": "", "comment": "",
|
||||
"cost_structure": None,
|
||||
"overhead": None, "profit": None, "coefficients": [],
|
||||
"resources": {"workers": [], "machines": [], "materials": []},
|
||||
}
|
||||
@@ -100,6 +101,8 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
rec["machinist_ch"] = p["machinist_ch"]
|
||||
rec["price_base"] = data.get("price_base", "")
|
||||
rec["price_cur"] = data.get("price_cur", "")
|
||||
rec["comment"] = scrub(p.get("comment", ""))
|
||||
rec["cost_structure"] = p.get("cost_structure")
|
||||
rec["overhead"] = p["overhead"]
|
||||
rec["profit"] = p["profit"]
|
||||
rec["coefficients"] = p["coefficients"][:5]
|
||||
@@ -138,7 +141,9 @@ def build(root: Path, out_dir: Path) -> dict:
|
||||
"norm_sets": sorted(rec["norm_sets"], key=rec["norm_sets"].get, reverse=True),
|
||||
"regions": sorted(rec["regions"], key=rec["regions"].get, reverse=True)[:5],
|
||||
"qty": qstat,
|
||||
"comment": rec["comment"],
|
||||
"unit_cost_cur": rec["unit_cost_cur"],
|
||||
"cost_structure": rec["cost_structure"],
|
||||
"labor_ch": rec["labor_ch"], "machinist_ch": rec["machinist_ch"],
|
||||
"price_base": rec["price_base"], "price_cur": rec["price_cur"],
|
||||
"overhead": rec["overhead"], "profit": rec["profit"],
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Юнит-тесты парсеров gge_deep на синтетических фикстурах (без SSD/сети).
|
||||
|
||||
Запуск: python3 tests/test_gge_deep.py (или pytest tests/test_gge_deep.py)
|
||||
Каждая фикстура — минимальный, но представительный XML каждой схемы .gge
|
||||
с заранее известными значениями; проверяем, что парсер извлекает их точно.
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from gge_deep import parse_estimate_full, parse_vor, parse_ka, scrub # noqa: E402
|
||||
|
||||
LSR_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="LocalEstimateResourceIndexMethod-3_01.xsd">
|
||||
<Object><Estimate>
|
||||
<Num>ЛСР-06-07-0-06-01</Num>
|
||||
<Region><RegionName>Тверская область</RegionName></Region>
|
||||
<PriceLevelBase><Year>2022</Year><Quarter>1</Quarter></PriceLevelBase>
|
||||
<PriceLevelCur><Year>2025</Year><Quarter>2</Quarter></PriceLevelCur>
|
||||
<Sections><Section><Items>
|
||||
<Item>
|
||||
<Cost>
|
||||
<Code>01-01-030-05</Code><Prefix>ГЭСН</Prefix>
|
||||
<Name>Разработка грунта бульдозерами</Name>
|
||||
<Unit>1000 м3</Unit><QuantityTotal>6.751</QuantityTotal>
|
||||
<Comment>(тестовый комментарий)</Comment>
|
||||
<PerUnit><LaborCosts>0</LaborCosts><MachinistLaborCosts>5.5</MachinistLaborCosts></PerUnit>
|
||||
<ResourcesInternal>
|
||||
<Machine>
|
||||
<Code>91.01.01-035</Code><Name>Бульдозеры 79 кВт</Name>
|
||||
<Consumption>5.5</Consumption><Unit>маш.-ч</Unit>
|
||||
<PricePerUnitBase>900</PricePerUnitBase><PricePerUnitCur>1224.81</PricePerUnitCur>
|
||||
<Index><Reason>1030</Reason><Value><IndexValue>1.38</IndexValue></Value></Index>
|
||||
<Machinist><Grade>6</Grade><Consumption>5.5</Consumption><PricePerUnitCur>541.85</PricePerUnitCur></Machinist>
|
||||
</Machine>
|
||||
</ResourcesInternal>
|
||||
<Totals><Current><Direct>65596.97</Direct><Machines>45477.81</Machines>
|
||||
<Materials>0</Materials><Salary>20119.16</Salary>
|
||||
<MachinistSalary>20119.16</MachinistSalary><WorkersSalary>0</WorkersSalary></Current></Totals>
|
||||
</Cost>
|
||||
<Overheads><Value>92</Value><Target>ФОТ</Target><Reason>Пр/812-001.1-1</Reason><PriceCur>18509</PriceCur></Overheads>
|
||||
<Profits><Value>46</Value><Target>ФОТ</Target><Reason>Пр/774-001.1</Reason></Profits>
|
||||
</Item>
|
||||
<Item><Material>
|
||||
<Code>ФСБЦ-02</Code><Name>Песок природный</Name><Unit>м3</Unit>
|
||||
<ConsumptionTotal>10</ConsumptionTotal><PricePerUnitCur>808.24</PricePerUnitCur>
|
||||
<IsReturnMat>false</IsReturnMat>
|
||||
</Material></Item>
|
||||
<Item><Transport>
|
||||
<Code>04-1</Code><Name>Погрузка в автотранспорт</Name><Unit>т</Unit>
|
||||
<QuantityTotal>5.63</QuantityTotal><PricePerUnitCur>267.49</PricePerUnitCur>
|
||||
</Transport></Item>
|
||||
</Items></Section></Sections>
|
||||
</Estimate></Object>
|
||||
</Construction>"""
|
||||
|
||||
VOR_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="QuantityTakeoff-3_01.xsd">
|
||||
<Num>960-06-1356-ПОС9.2.ВОР17</Num><Reason>Раздел 5</Reason>
|
||||
<Sections><Section><Name>Открытая прокладка (Московская область)</Name>
|
||||
<Works><Work>
|
||||
<Name>Снятие почвенно-растительного слоя</Name><Unit>м3</Unit>
|
||||
<Quantity>147.3</Quantity><QuantityFormula>147.3*1</QuantityFormula>
|
||||
<Links><Link><PageDescription>960-06-1356-ПОС9.2-ГЧ.3</PageDescription><PageNumber>173</PageNumber></Link></Links>
|
||||
</Work></Works>
|
||||
</Section></Sections>
|
||||
</Construction>"""
|
||||
|
||||
KA_XML = """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="MarketAnalysis-3_01.xsd">
|
||||
<ObjectName>Создание высокоскоростной магистрали</ObjectName>
|
||||
<Items><Item>
|
||||
<Name>Распашные ворота 4000x2500</Name><Unit>шт</Unit><Type>оборудование</Type>
|
||||
<Offer>
|
||||
<OfferCompany><CompanyName>ООО Ромашка</CompanyName><INN>9722010798</INN></OfferCompany>
|
||||
<OfferPrice><OfferUnitWithoutVAT>90000</OfferUnitWithoutVAT>
|
||||
<EstimateWithoutVAT>94554</EstimateWithoutVAT><OfferWithVAT>108000</OfferWithVAT>
|
||||
<DeliveryTerms>без учета перевозки</DeliveryTerms></OfferPrice>
|
||||
<Storage><Price>1854</Price></Storage><Transportation><Price>2700</Price></Transportation>
|
||||
<Region><Name>г. Москва</Name></Region>
|
||||
<OfferDate><Year>2024</Year><Quarter>4</Quarter></OfferDate>
|
||||
<OriginCountry>РФ</OriginCountry><Winner>true</Winner>
|
||||
</Offer>
|
||||
</Item></Items>
|
||||
</Construction>"""
|
||||
|
||||
|
||||
def _write(tmp, name, xml):
|
||||
p = tmp / name
|
||||
p.write_text(xml, encoding="utf-8")
|
||||
return p
|
||||
|
||||
|
||||
def test_parse_estimate_full(tmp_path):
|
||||
d = parse_estimate_full(_write(tmp_path, "lsr.gge", LSR_XML))
|
||||
assert d["code"] == "ЛСР-06-07-0-06-01"
|
||||
assert d["region"] == "Тверская область"
|
||||
assert d["price_base"] == "2022 Q1" and d["price_cur"] == "2025 Q2"
|
||||
pos = [p for p in d["positions"] if p["kind"] == "cost"]
|
||||
assert len(pos) == 1
|
||||
p = pos[0]
|
||||
assert p["code"] == "01-01-030-05" and p["prefix"] == "ГЭСН"
|
||||
assert p["comment"] == "(тестовый комментарий)"
|
||||
assert p["machinist_ch"] == 5.5
|
||||
assert round(p["unit_cost_cur"], 2) == round(65596.97 / 6.751, 2)
|
||||
assert p["cost_structure"]["machines"] == 45477.81
|
||||
assert p["cost_structure"]["salary"] == 20119.16
|
||||
assert p["overhead"] == {"value": "92", "target": "ФОТ",
|
||||
"reason": "Пр/812-001.1-1", "price_cur": 18509.0}
|
||||
assert p["profit"]["value"] == "46"
|
||||
m = p["resources"]["machines"][0]
|
||||
assert m["code"] == "91.01.01-035" and m["price_cur"] == 1224.81
|
||||
assert m["index"] == {"value": 1.38, "reason": "1030"}
|
||||
assert m["machinist"] == {"consumption": 5.5, "price_cur": 541.85, "grade": "6"}
|
||||
# прямой материал + Transport
|
||||
assert d["direct_materials"][0]["name"] == "Песок природный"
|
||||
assert d["direct_materials"][0]["is_return"] is False
|
||||
tr = [p for p in d["positions"] if p["kind"] == "transport"][0]
|
||||
assert tr["unit_cost_cur"] == 267.49 # фикс: цена из PricePerUnitCur, не 0
|
||||
|
||||
|
||||
def test_parse_vor(tmp_path):
|
||||
d = parse_vor(_write(tmp_path, "vor.gge", VOR_XML))
|
||||
assert d["num"] == "960-06-1356-ПОС9.2.ВОР17" # raw, обезличивание в индексаторе
|
||||
assert len(d["works"]) == 1
|
||||
w = d["works"][0]
|
||||
assert w["name"] == "Снятие почвенно-растительного слоя"
|
||||
assert w["unit"] == "м3" and w["quantity"] == 147.3
|
||||
assert w["formula"] == "147.3*1"
|
||||
assert "ПОС9.2-ГЧ.3" in w["source"] and "л.173" in w["source"]
|
||||
|
||||
|
||||
def test_parse_ka(tmp_path):
|
||||
items = parse_ka(KA_XML.encode("utf-8"))
|
||||
assert len(items) == 1
|
||||
it = items[0]
|
||||
assert it["name"] == "Распашные ворота 4000x2500" and it["type"] == "оборудование"
|
||||
o = it["offers"][0]
|
||||
assert o["vendor"] == "Поставщик 1" # обезличено уже в парсере
|
||||
assert o["market_price"] == 90000.0
|
||||
assert o["estimate_price"] == 94554.0 # сметная цена — ключевое
|
||||
assert o["storage"] == 1854.0 and o["transport"] == 2700.0
|
||||
assert o["winner"] is True
|
||||
# реквизиты поставщика НЕ протекают в оффер
|
||||
blob = str(o)
|
||||
assert "Ромашка" not in blob and "9722010798" not in blob
|
||||
|
||||
|
||||
def test_scrub():
|
||||
assert scrub("960-06-1356-СМ3.8.1") == "[…]"
|
||||
assert scrub("Кабель 960-06-ТКР34") == "Кабель […]"
|
||||
assert scrub("Опора на ПК5555+94 моста") == "Опора на […] моста"
|
||||
assert scrub("ст. Новая Тверь ВСМ") == "ст. […] […]"
|
||||
# бренды товаров и регион поставщика НЕ трогаем
|
||||
assert scrub("Лоток ЭНЕРГОТЭК ПК-3 100x100") == "Лоток ЭНЕРГОТЭК ПК-3 100x100"
|
||||
assert scrub("Поставщик из Санкт-Петербурга") == "Поставщик из Санкт-Петербурга"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import tempfile
|
||||
passed = 0
|
||||
for fn in (test_parse_estimate_full, test_parse_vor, test_parse_ka):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
fn(Path(td))
|
||||
passed += 1
|
||||
print(f"OK {fn.__name__}")
|
||||
test_scrub()
|
||||
passed += 1
|
||||
print(f"OK test_scrub")
|
||||
print(f"\n{passed}/4 тестов прошли")
|
||||
Reference in New Issue
Block a user