88 lines
3.0 KiB
Python

"""Whitelisted API for SFDA scraper and ADE PublishDetails preview."""
from __future__ import annotations
import frappe
from sfda_parser.sfda_scraper.detail_page import (
fetch_publish_details,
resolve_detail_url_for_ncmdr_ref,
)
from sfda_parser.sfda_scraper.importer import import_latest_weekly_alerts
from sfda_parser.sfda_scraper.reparse import reparse_all_stored_pdf_device_lists
@frappe.whitelist()
def run_sfda_scraper_now():
frappe.only_for("System Manager")
return import_latest_weekly_alerts()
@frappe.whitelist()
def reparse_device_list_from_stored_pdfs(sfda_entries_name: str | None = None):
"""Rebuild Device List child rows from stored detail_pdf using current PDF parser."""
frappe.only_for("System Manager")
return reparse_all_stored_pdf_device_lists(sfda_entries_name=sfda_entries_name)
@frappe.whitelist()
def get_ade_publish_details(
detail_url: str | None = None,
sfda_entries_name: str | None = None,
sfda_device_entry_name: str | None = None,
ncmdr_ref: str | None = None,
include_device_list_from_pdf: int | str = 0,
):
"""
Load ADE PublishDetails via the ERP server (works when your PC browser is blocked).
Pass detail_url and/or sfda_entries_name with a child row reference.
"""
include_pdf = str(include_device_list_from_pdf).lower() in ("1", "true", "yes")
url = (detail_url or "").strip()
if sfda_entries_name and not url:
doc = frappe.get_doc("SFDA Entries", sfda_entries_name)
child_row = None
if sfda_device_entry_name:
child_row = next(
(row for row in doc.device_list if row.name == sfda_device_entry_name),
None,
)
elif ncmdr_ref:
target = (ncmdr_ref or "").strip().upper()
child_row = next(
(
row
for row in doc.device_list
if (row.ncmdr_ref or "").strip().upper() == target
),
None,
)
if child_row:
url = (child_row.get("ade_detail_url") or "").strip()
if not url and child_row.ncmdr_ref:
url = resolve_detail_url_for_ncmdr_ref(child_row.ncmdr_ref) or ""
if url:
child_row.ade_detail_url = url
doc.save(ignore_permissions=True)
if not url:
frappe.throw(
"No ADE URL available. Pass detail_url, select a device row with an ADE URL, "
"or re-run the weekly import."
)
if not url.startswith("http"):
url = f"https://ade.sfda.gov.sa/Fsca/PublishDetails/{url}"
try:
return fetch_publish_details(url, include_device_list_from_pdf=include_pdf)
except Exception as exc:
frappe.log_error(title="SFDA: ADE fetch failed", message=f"URL: {url}\n{exc}")
frappe.throw(
f"Could not load ADE from the server: {exc}. "
"The site may be blocked on your PC but reachable from ERP."
)