File size: 11,541 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""Oracle's quarterly What's New for a Fusion release, read from docs.oracle.com (public content only).



Each product publishes a guide at https://docs.oracle.com/en/cloud/saas/readiness/<family>/<rel>/<product><rel>/ (for

example erp/26c/fins26c for Financials 26C). Its "Feature Summary" page is a table: Module | Feature | Tags | Impact to

Existing Processes | Action to Enable, each feature linking to its own page. This module reads that table (no model),

picks the rows of one business area (platform/fusion_catalog.py `readiness`), and adds the opening text of each

feature's page. A guide Oracle has not published answers with a redirect to the readiness home page: reported as not

published, never mistaken for content.



Features whose Action to Enable is "None" are switched on by the update itself: they change what users see without

anyone opting in, so they come first. The result is cached per release and guide (public data); a cached guide is

never fetched again."""
from __future__ import annotations

import html
import json
import re
import threading
from datetime import datetime, timezone
from html.parser import HTMLParser
from pathlib import Path
from typing import Callable

BASE = "https://docs.oracle.com/en/cloud/saas/readiness"
RELEASE_RE = re.compile(r"^\d{2}[A-Da-d]$")
MAX_DETAILS = 30          # feature pages read per area (the most relevant first)
DETAIL_CHARS = 1500

_LOCKS: dict[str, threading.Lock] = {}
_LOCKS_GUARD = threading.Lock()


def _guide_lock(key: str) -> threading.Lock:
    """One reader per guide: areas sharing a guide (Payables, Receivables, Ledger read Financials) researched at the

    same time wait for the first, then use its saved copy."""
    with _LOCKS_GUARD:
        return _LOCKS.setdefault(key, threading.Lock())


Fetch = Callable[[str], tuple[int, str]]   # url -> (HTTP status, text); a redirect is a status 3xx, not followed


class NotPublished(LookupError):
    pass


def _now() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def release_code(release: str | None) -> str | None:
    """'26C' / '26c' -> '26c'; anything else (unknown, a patch name) -> None."""
    r = (release or "").strip()
    return r.lower() if RELEASE_RE.match(r) else None


def guide_base(family: str, product: str, rel: str) -> str:
    return f"{BASE}/{family}/{rel}/{product}{rel}/"


class _Table(HTMLParser):
    """Rows of the Feature Summary table: [(cells as text, first link of each cell)]."""
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.rows: list[tuple[list[str], list[str | None]]] = []
        self._cells: list[str] | None = None
        self._links: list[str | None] = []
        self._cell: list[str] | None = None

    def handle_starttag(self, tag, attrs):
        if tag == "tr":
            self._cells, self._links = [], []
        elif tag in ("td", "th") and self._cells is not None:
            self._cell = []
            self._links.append(None)
        elif tag == "a" and self._cell is not None and self._links and self._links[-1] is None:
            self._links[-1] = dict(attrs).get("href")

    def handle_endtag(self, tag):
        if tag in ("td", "th") and self._cell is not None and self._cells is not None:
            self._cells.append(re.sub(r"\s+", " ", "".join(self._cell)).strip())
            self._cell = None
        elif tag == "tr" and self._cells is not None:
            if self._cells:
                self.rows.append((self._cells, self._links))
            self._cells = None

    def handle_data(self, data):
        if self._cell is not None:
            self._cell.append(data)


def _summary_href(toc: str) -> str | None:
    for href, text in re.findall(r'<a[^>]+href="([^"#]+\.htm)[^"]*"[^>]*>(.*?)</a>', toc, flags=re.S):
        if re.sub(r"<[^>]+>|\s+", " ", html.unescape(text)).strip().lower() == "feature summary":
            return href
    return None


def parse_summary(page: str, base: str) -> list[dict]:
    """The Feature Summary table as rows {module, feature, url, tags, impact, action, on_by_default}."""
    t = _Table()
    t.feed(page)
    out, header = [], None
    for cells, links in t.rows:
        low = [c.lower() for c in cells]
        if "module" in low and "feature" in low:
            header = low
            continue
        if not header or len(cells) < 2:
            continue
        col = {name: i for i, name in enumerate(header)}
        get = lambda name: cells[col[name]] if name in col and col[name] < len(cells) else ""   # noqa: E731
        fi = col.get("feature", 1)
        href = links[fi] if fi < len(links) else None
        action = next((get(k) for k in col if k.startswith("action")), "")
        impact = next((get(k) for k in col if k.startswith("impact")), "")
        out.append({"module": get("module"), "feature": get("feature"),
                    "url": (base + href.split("#")[0]) if href and not href.startswith("http") else href,
                    "id": (re.search(r"(f\d+)\.htm", href or "") or [None, None])[1],
                    "tags": get("tags"), "impact": impact, "action": action,
                    "on_by_default": action.strip().lower() in ("none", "")})
    return out


def page_text(page: str) -> str:
    """A feature page's own words: the article body without navigation, scripts and the no-JavaScript notice."""
    m = re.search(r"<article.*?</article>|<main.*?</main>|<body.*?</body>", page, flags=re.S)
    b = re.sub(r"<script.*?</script>|<style.*?</style>|<nav.*?</nav>|<header.*?</header>|<footer.*?</footer>", "",
               m.group(0) if m else page, flags=re.S)
    lines = [l.strip() for l in html.unescape(re.sub(r"<[^>]+>", "\n", b)).split("\n")]
    skip = {"previous", "next", "javascript must be enabled to correctly display this content"}
    return re.sub(r"\s+", " ", " ".join(l for l in lines if l and l.lower() not in skip))[:DETAIL_CHARS]


def read_guide(fetch: Fetch, family: str, product: str, rel: str) -> dict:
    """{"url", "features": [...]} of one guide. Raises NotPublished when Oracle has no such guide (yet)."""
    base = guide_base(family, product, rel)
    status, toc = fetch(base + "toc.htm")
    if status != 200:
        raise NotPublished(f"Oracle has not published the {product.upper()} {rel.upper()} What's New ({base})")
    href = _summary_href(toc)
    if not href:
        raise NotPublished(f"the {product.upper()} {rel.upper()} What's New has no Feature Summary page ({base})")
    status, page = fetch(base + href)
    if status != 200:
        raise NotPublished(f"the {product.upper()} {rel.upper()} Feature Summary did not load (HTTP {status})")
    return {"url": base + "index.html", "features": parse_summary(page, base), "read_at": _now()}


def area_rows(guide: dict, match: list[str], others: list[str] | None = None) -> list[dict]:
    """The guide's rows for one area: every row when `match` is empty. Otherwise the Module column decides (a row whose

    module names the area); a feature's title counts only when its module belongs to no area of the guide (shared

    modules such as Local Compliance & Reporting), so a lease feature about payments is not a Payables change.

    `others` = the match words of the other areas reading the same guide."""
    if not match:
        return list(guide["features"])
    mine = [m.lower() for m in match]
    every = mine + [m.lower() for m in others or []]
    has = lambda text, words: any(w in text.lower() for w in words)   # noqa: E731
    return [f for f in guide["features"]
            if has(f["module"], mine) or (not has(f["module"], every) and has(f["feature"], mine))]


def to_changes(rows: list[dict], rel: str, area_code: str) -> list[dict]:
    """Research `changes` items (llm/schemas.ChangeItemModel fields) with the release's own facts in the summary."""
    out = []
    rows = sorted(rows, key=lambda f: (not f["on_by_default"], f["module"], f["feature"]))
    for f in rows:
        how = "on automatically with the update" if f["on_by_default"] else f"needs action to enable ({f['action']})"
        bits = [f"{f['feature']}.", f"{how[0].upper()}{how[1:]}."]
        if f["impact"] and f["impact"].lower() != "none":
            bits.append(f"Impact to existing processes: {f['impact']}.")
        if f.get("detail"):
            bits.append(f["detail"])
        out.append({"id": f"{rel.upper()}-{area_code}-{f['id'] or len(out) + 1}", "area": f["module"] or area_code,
                    "summary": " ".join(bits)[:2000], "map_rows": [],
                    "sources": [{"url": f["url"] or "", "title": f"Oracle {rel.upper()} What's New: {f['feature']}"[:200],
                                 "kind": "oracle_doc", "verified": "DOC-LINK"}],
                    "confidence": 0.9 if f.get("detail") else 0.8,
                    "on_by_default": f["on_by_default"], "action": f["action"], "impact": f["impact"], "tags": f["tags"]})
    return out


def changes_for(fetch: Fetch, area: dict, release: str, cache_dir: Path, catalog: list[dict] | None = None) -> dict:
    """{"changes": [...], "guide": url, "release": "26C", "source": "oracle" | "cache"} for one catalog area.

    Raises NotPublished (no guide for that release) or ValueError (no usable release)."""
    rel = release_code(release)
    if not rel:
        raise ValueError(f"'{release}' is not an Oracle Fusion release such as 26C: set the release on the pod")
    spec = area.get("readiness") or {}
    if not spec.get("family") or not spec.get("product"):
        raise NotPublished(f"no What's New guide is known for {area['name']}")
    cache = Path(cache_dir) / rel.upper() / "_guides" / f"{spec['family']}-{spec['product']}.json"
    with _guide_lock(str(cache)):
        if cache.is_file():
            guide, source = json.loads(cache.read_text(encoding="utf-8")), "cache"
        else:
            guide, source = read_guide(fetch, spec["family"], spec["product"], rel), "oracle"
        same = [a for a in catalog or [] if a["code"] != area["code"] and (a.get("readiness") or {}).get("product") == spec["product"]
                and (a.get("readiness") or {}).get("family") == spec["family"]]
        rows = area_rows(guide, spec.get("match") or [], [w for a in same for w in a["readiness"].get("match") or []])
        # the opening text of the most relevant features (on by default first), read once and kept in the guide's cache
        wanted = sorted(rows, key=lambda f: (not f["on_by_default"], f["feature"]))[:MAX_DETAILS]
        fetched = False
        for f in wanted:
            if "detail" in f or not f.get("url"):
                continue
            try:
                status, page = fetch(f["url"])
                f["detail"] = page_text(page) if status == 200 else ""
            except Exception:  # noqa: BLE001  (a page that does not load leaves the feature without its text)
                f["detail"] = ""
            fetched = True
        if source == "oracle" or fetched:   # the area's rows are the guide's own entries: their text is saved with it
            cache.parent.mkdir(parents=True, exist_ok=True)
            cache.write_text(json.dumps(guide, indent=1), encoding="utf-8")
        return {"changes": to_changes(rows, rel, area["code"]), "guide": guide["url"], "release": rel.upper(), "source": source}