This commit is contained in:
timur 2026-10-06 22:59:40 +05:00
parent 50688f97be
commit 5088673692
1 changed files with 36 additions and 12 deletions

View File

@ -51,6 +51,9 @@ def arguments() -> argparse.Namespace:
default=[],
help="ограничить выгрузку набором Document_* (можно указать несколько раз)",
)
parser.add_argument(
"--limit", type=int, default=10, help="максимум документов в результате (по умолчанию 10)"
)
parser.add_argument("--timeout", type=float, default=30, help="таймаут HTTP в секундах")
return parser.parse_args()
@ -92,11 +95,15 @@ class ODataClient:
def all_pages(self, url: str) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for page in self.iter_pages(url):
result.extend(page)
return result
def iter_pages(self, url: str):
while url:
page, next_url = self.json_page(url)
result.extend(page)
yield page
url = urllib.parse.urljoin(self.root + "/", next_url) if next_url else ""
return result
def entity_url(self, entity: str, params: dict[str, str]) -> str:
quoted_entity = urllib.parse.quote(entity, safe="_()")
@ -236,13 +243,18 @@ def fetch_documents(
reference_field: str,
client_key: str,
from_date: str | None,
limit: int,
) -> list[dict[str, Any]]:
filters = [f"{reference_field} eq guid'{client_key}'"]
if from_date:
filters.append(f"Date ge datetime'{from_date}T00:00:00'")
filtered_url = api.entity_url(entity, {"$filter": " and ".join(filters), "$format": "json"})
filtered_url = api.entity_url(
entity,
{"$filter": " and ".join(filters), "$top": str(limit), "$format": "json"},
)
try:
return api.all_pages(filtered_url)
rows = api.all_pages(filtered_url)
return rows[:limit]
except RuntimeError as filter_error:
if "Операция не разрешена" not in str(filter_error) or "ГДЕ" not in str(filter_error):
raise
@ -250,20 +262,27 @@ def fetch_documents(
f"{entity}: фильтрация ссылки в 1С запрещена, выполняется локальный отбор...",
file=sys.stderr,
)
rows = api.all_pages(api.entity_url(entity, {"$format": "json"}))
normalized_key = client_key.casefold()
return [
row
for row in rows
if str(row.get(reference_field, "")).casefold() == normalized_key
and date_is_not_earlier(row.get("Date"), from_date)
]
matches: list[dict[str, Any]] = []
unfiltered_url = api.entity_url(entity, {"$format": "json"})
for page in api.iter_pages(unfiltered_url):
for row in page:
if (
str(row.get(reference_field, "")).casefold() == normalized_key
and date_is_not_earlier(row.get("Date"), from_date)
):
matches.append(row)
if len(matches) >= limit:
return matches
return matches
def main() -> int:
args = arguments()
if bool(args.client) == bool(args.inn):
raise RuntimeError("укажите либо наименование клиента, либо --inn")
if args.limit < 1:
raise RuntimeError("--limit должен быть больше нуля")
if args.from_date:
try:
datetime.strptime(args.from_date, "%Y-%m-%d")
@ -295,8 +314,13 @@ def main() -> int:
exported: dict[str, list[dict[str, Any]]] = {}
failures: dict[str, str] = {}
for entity, reference_field in documents:
remaining = args.limit - sum(len(rows) for rows in exported.values())
if remaining <= 0:
break
try:
rows = fetch_documents(api, entity, reference_field, str(client_key), args.from_date)
rows = fetch_documents(
api, entity, reference_field, str(client_key), args.from_date, remaining
)
exported[entity] = rows
print(f"{entity}: {len(rows)}", file=sys.stderr)
except (RuntimeError, ValueError, json.JSONDecodeError) as error: