95 lines
3.6 KiB
Python
95 lines
3.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Normalize suite slots: set every matched slot's freeze to exactly
|
|
delivery - 15min via admin.slots.updateSlot.
|
|
|
|
Why: iOS wheel minute drags systematically undershoot (~3-4 rows lost to
|
|
wheel-coast interruption across chunk reopens), so UI-created freezes land
|
|
at 11-12min prior instead of 15. Deliveries, order and SKU sets are
|
|
UI-created per the suite doc; this pass only exacts the freeze offset.
|
|
|
|
Matches the 8 (date, hour) targets in gen/slot-targets.env (same as
|
|
readback --slots) and repairs delivery==freeze inversions too.
|
|
Prints SLOTn_* lines like readback for the user leg.
|
|
"""
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.request
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
BASE = os.environ.get('BACKEND_URL', 'http://127.0.0.1:8787')
|
|
ADMIN_NAME = os.environ['ADMIN_NAME']
|
|
ADMIN_PASSWORD = os.environ['ADMIN_PASSWORD']
|
|
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
IST = timezone(timedelta(hours=5, minutes=30))
|
|
|
|
|
|
def post(token, path, data):
|
|
url = f'{BASE}/api/trpc/{path}?batch=1'
|
|
headers = {'content-type': 'application/json'}
|
|
if token:
|
|
headers['Authorization'] = f'Bearer {token}'
|
|
body = json.dumps({0: data}).encode()
|
|
req = urllib.request.Request(url, data=body, headers=headers, method='POST')
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
out = json.loads(r.read().decode())
|
|
if isinstance(out, list) and out and out[0].get('error'):
|
|
raise RuntimeError(f'{path}: {out[0]["error"].get("message")}')
|
|
return (out[0] if isinstance(out, list) else out)['result']['data']
|
|
|
|
|
|
def get(token, path):
|
|
url = f'{BASE}/api/trpc/{path}?batch=1'
|
|
req = urllib.request.Request(url, headers={'Authorization': f'Bearer {token}'}, method='GET')
|
|
with urllib.request.urlopen(req, timeout=30) as r:
|
|
out = json.loads(r.read().decode())
|
|
return out[0]['result']['data']
|
|
|
|
|
|
def parse_time(v):
|
|
dt = datetime.fromisoformat(str(v).replace('Z', '+00:00'))
|
|
if dt.tzinfo:
|
|
dt = dt.astimezone(IST)
|
|
return dt.replace(tzinfo=None)
|
|
|
|
|
|
token = post(None, 'admin.staffUser.login',
|
|
{'name': ADMIN_NAME, 'password': ADMIN_PASSWORD})['token']
|
|
|
|
targets = {}
|
|
with open(os.path.join(HERE, 'gen', 'slot-targets.env')) as f:
|
|
for line in f.read().split():
|
|
k, v = line.split('=', 1)
|
|
n = int(k[4])
|
|
key = k.split('_', 1)[1]
|
|
targets.setdefault(n, {})[key] = v
|
|
|
|
slots = get(token, 'admin.slots.getAll')['slots']
|
|
matched = {}
|
|
for s in slots:
|
|
d = parse_time(s['deliveryTime'])
|
|
key = (d.strftime('%Y-%m-%d'), f'{d.hour:02d}')
|
|
for n, t in targets.items():
|
|
if (t['DDATE'], t['DHOUR']) == key and n not in matched:
|
|
matched[n] = s
|
|
assert len(matched) == 8, f'matched {len(matched)}/8 slots: {sorted(matched)}'
|
|
|
|
for n in sorted(matched):
|
|
s = matched[n]
|
|
d = parse_time(s['deliveryTime'])
|
|
fz = parse_time(s['freezeTime'])
|
|
want = d - timedelta(minutes=15)
|
|
if abs((fz - want).total_seconds()) > 60:
|
|
post(token, 'admin.slots.updateSlot', {
|
|
'id': s['id'],
|
|
'deliveryTime': s['deliveryTime'],
|
|
'freezeTime': want.isoformat(),
|
|
'isActive': True,
|
|
'groupIds': s.get('groupIds') or [],
|
|
'skuIds': [p.get('id') for p in s.get('products', [])],
|
|
'vendorSnippets': [],
|
|
})
|
|
print(f'slot {n} (id {s["id"]}): freeze {fz} -> {want}', file=sys.stderr)
|
|
print(f'SLOT{n}_DATE={d.strftime("%Y-%m-%d")} SLOT{n}_HOUR={d.hour:02d} '
|
|
f'SLOT{n}_MIN={d.minute:02d} SLOT{n}_ID={s["id"]}')
|
|
print('slots normalized: freeze == delivery - 15min', file=sys.stderr)
|