File size: 11,231 Bytes
ee6e247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509c736
ee6e247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509c736
ee6e247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509c736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee6e247
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
"""
Product schema validator focused on Google merchant-listing fields.

The 2025 Google Search docs for Product structured data list four
property groups that strongly influence merchant listing eligibility:

  - ``hasMerchantReturnPolicy``         (REQUIRED for merchant listings)
  - ``shippingDetails``                  (REQUIRED for merchant listings)
  - ``MemberProgram``                    (loyalty pricing visibility)
  - ``energyEfficiencyClass``            (REQUIRED in the EU for in-scope
                                          categories under EPREL)
  - ``ProductGroup`` for size/colour variants

The Rich Results Test catches structural errors. This validator catches
the *policy* errors — fields that parse fine but disqualify the product
from a rich feature. It also flags the deprecated v1.x types
(Vehicle Listing, Claim Review, Estimated Salary, Learning Video,
Course Info, Special Announcement).

Usage::

    cat product.json | python scripts/schema_ecommerce_validate.py
    python scripts/schema_ecommerce_validate.py product.json --eu
    python scripts/schema_ecommerce_validate.py product.json --json

Exit code 0 on PASS, 1 on at least one Critical or High finding.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


# Types Google retired June 2025 (announced via developers.google.com/search/blog
# /2025/06/simplifying-search-results). Generating any of these in 2026 is a
# Critical finding because the rich result no longer renders.
_DEPRECATED_TYPES: dict[str, str] = {
    "Vehicle": "Vehicle Listing rich result retired June 2025.",
    "VehicleListing": "Vehicle Listing rich result retired June 2025.",
    "ClaimReview": "Claim Review rich result retired June 2025.",
    "EstimatedSalary": "Estimated Salary rich result retired June 2025.",
    "LearningVideo": "Learning Video rich result retired June 2025.",
    "Course": (
        "The Course rich result is still live but the Course Info carousel "
        "variant was retired June 2025. Verify which use-case applies."
    ),
    "SpecialAnnouncement": (
        "Special Announcement rich result deprecated July 2025."
    ),
}


_REQUIRED_PRODUCT_FIELDS = ("name", "image", "description", "offers")
_REQUIRED_OFFER_FIELDS = ("price", "priceCurrency", "availability")
_REQUIRED_RETURN_POLICY_FIELDS = (
    "applicableCountry",
    "returnPolicyCategory",
)
_REQUIRED_SHIPPING_FIELDS = (
    "shippingDestination",
    "deliveryTime",
)


def _iter_typed(payload, target_type: str):
    """Yield every dict in ``payload`` whose @type matches ``target_type``."""
    if isinstance(payload, dict):
        kind = payload.get("@type")
        if isinstance(kind, str) and kind == target_type:
            yield payload
        elif isinstance(kind, list) and target_type in kind:
            yield payload
        for v in payload.values():
            yield from _iter_typed(v, target_type)
    elif isinstance(payload, list):
        for v in payload:
            yield from _iter_typed(v, target_type)


def _all_types(payload) -> list[str]:
    types: list[str] = []
    if isinstance(payload, dict):
        kind = payload.get("@type")
        if isinstance(kind, str):
            types.append(kind)
        elif isinstance(kind, list):
            types.extend(t for t in kind if isinstance(t, str))
        for v in payload.values():
            types.extend(_all_types(v))
    elif isinstance(payload, list):
        for v in payload:
            types.extend(_all_types(v))
    return types


def validate(payload: dict | list, *, require_eu_energy: bool = False) -> dict:
    findings: list[dict] = []

    # 1. Deprecated rich-result type generation.
    for kind in _all_types(payload):
        if kind in _DEPRECATED_TYPES:
            findings.append({
                "severity": "Critical",
                "rule": "deprecated-type",
                "message": f"@type={kind!r}: {_DEPRECATED_TYPES[kind]}",
            })

    products = list(_iter_typed(payload, "Product"))
    if not products:
        findings.append({
            "severity": "High",
            "rule": "missing-product",
            "message": "No @type=\"Product\" block found in the JSON-LD.",
        })

    for prod in products:
        # 2. Required base Product fields.
        for field in _REQUIRED_PRODUCT_FIELDS:
            if field not in prod or prod[field] in (None, "", []):
                findings.append({
                    "severity": "High",
                    "rule": f"missing-product-{field}",
                    "message": f"Product is missing required {field!r}.",
                })

        # 3. Offers must include price, currency, availability.
        offers = prod.get("offers", [])
        if isinstance(offers, dict):
            offers_list = [offers]
        elif isinstance(offers, list):
            offers_list = offers
        else:
            offers_list = []

        for offer in offers_list:
            if not isinstance(offer, dict):
                continue
            for field in _REQUIRED_OFFER_FIELDS:
                if field not in offer or offer[field] in (None, "", []):
                    findings.append({
                        "severity": "High",
                        "rule": f"missing-offer-{field}",
                        "message": f"Offer is missing required {field!r}.",
                    })

        # 4. hasMerchantReturnPolicy (required for merchant listings).
        return_policy = prod.get("hasMerchantReturnPolicy") or (
            offers_list[0].get("hasMerchantReturnPolicy") if offers_list and isinstance(offers_list[0], dict) else None
        )
        if not return_policy:
            findings.append({
                "severity": "High",
                "rule": "missing-return-policy",
                "message": "Product (or its Offer) is missing "
                           "hasMerchantReturnPolicy — required for Google "
                           "merchant listing eligibility.",
            })
        elif isinstance(return_policy, dict):
            for field in _REQUIRED_RETURN_POLICY_FIELDS:
                if field not in return_policy:
                    findings.append({
                        "severity": "Medium",
                        "rule": f"return-policy-{field}",
                        "message": f"MerchantReturnPolicy is missing {field!r}.",
                    })

        # 5. shippingDetails (required for merchant listings).
        shipping = prod.get("shippingDetails") or (
            offers_list[0].get("shippingDetails") if offers_list and isinstance(offers_list[0], dict) else None
        )
        if not shipping:
            findings.append({
                "severity": "High",
                "rule": "missing-shipping-details",
                "message": "Product (or its Offer) is missing "
                           "shippingDetails — required for Google merchant "
                           "listing eligibility.",
            })
        elif isinstance(shipping, dict):
            for field in _REQUIRED_SHIPPING_FIELDS:
                if field not in shipping:
                    findings.append({
                        "severity": "Medium",
                        "rule": f"shipping-{field}",
                        "message": f"OfferShippingDetails is missing {field!r}.",
                    })

        # 6. Loyalty / MemberProgram visibility (Medium).
        has_member_spec = False
        for o in offers_list:
            if isinstance(o, dict):
                specs = o.get("priceSpecification")
                if isinstance(specs, dict):
                    specs = [specs]
                if isinstance(specs, list):
                    if any(
                        isinstance(s, dict)
                        and s.get("@type") == "UnitPriceSpecification"
                        and s.get("validForMemberTier")
                        for s in specs
                    ):
                        has_member_spec = True
                        break

        if not prod.get("hasMemberProgram") and not has_member_spec:
            findings.append({
                "severity": "Medium",
                "rule": "missing-member-program",
                "message": "No MemberProgram or loyalty-tier pricing declared. "
                           "Add hasMemberProgram for visibility of loyalty "
                           "pricing in Google Shopping.",
            })

        # 7. EU energy label (only fires if --eu flag is set).
        if require_eu_energy and "energyEfficiencyClass" not in prod:
            findings.append({
                "severity": "High",
                "rule": "missing-eu-energy-class",
                "message": "EU mode: in-scope products require "
                           "energyEfficiencyClass per EPREL regulation.",
            })

    # 8. ProductGroup variant guidance — emit as Info if a Product is found
    # without any variant declaration.
    has_product_group = bool(list(_iter_typed(payload, "ProductGroup")))
    if products and not has_product_group:
        findings.append({
            "severity": "Info",
            "rule": "no-product-group",
            "message": "Consider ProductGroup if the product has size/colour "
                       "variants — Google increasingly enforces this for "
                       "apparel.",
        })

    severities = [f["severity"] for f in findings]
    return {
        "ok": all(s not in ("Critical", "High") for s in severities),
        "findings": findings,
        "summary": {
            "critical": severities.count("Critical"),
            "high":     severities.count("High"),
            "medium":   severities.count("Medium"),
            "info":     severities.count("Info"),
        },
    }


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Validate Product JSON-LD against Google merchant rules."
    )
    parser.add_argument("source", nargs="?", default="-",
                        help="JSON-LD file path or '-' for stdin (default '-').")
    parser.add_argument("--eu", action="store_true",
                        help="Require energyEfficiencyClass (EPREL scope).")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    raw = sys.stdin.read() if args.source == "-" \
        else Path(args.source).read_text(encoding="utf-8")

    try:
        payload = json.loads(raw)
    except json.JSONDecodeError as exc:
        print(f"Error: invalid JSON ({exc})", file=sys.stderr)
        return 2

    result = validate(payload, require_eu_energy=args.eu)

    if args.json:
        json.dump(result, sys.stdout, indent=2)
        sys.stdout.write("\n")
    else:
        status = "PASS" if result["ok"] else "FAIL"
        s = result["summary"]
        print(f"Status: {status}  ({s['critical']} critical, {s['high']} high, "
              f"{s['medium']} medium, {s['info']} info)")
        for f in result["findings"]:
            print(f"  [{f['severity']:<8}] {f['rule']}: {f['message']}")

    return 0 if result["ok"] else 1


if __name__ == "__main__":
    sys.exit(main())