#!/usr/bin/env python3 """Generate gen/admin-slots.yaml: 8 slots, 2h apart, freeze 15min prior. Timing model (iOS compact UIDatePicker, verified by spike): - Every date/time picker opens at *now*. Dates: calendar nav via DatePicker.NextMonth + day tap + Done. Hours/minutes: tap wheel values (each tap moves exactly one step; values recenter after every tap). - Delivery minute: left at whatever the wheel shows (0 taps). Freeze minute: always 15 taps DOWN from open minute (relative, so immune to drift). - Delivery/freeze hour walks are absolute from gen-time hour; the YAML is generated seconds before the flow runs, and readback.py verifies every slot afterwards (fail fast on hour-boundary rollover). Env in: STAMP, P1, P2, COMBO (product names for search), TZ implied IST. Files out: gen/admin-slots.yaml, gen/slot-targets.env (SLOTn_DDATE/DHOUR/ FDATE/FHOUR as YYYY-MM-DD + 24h hour, for readback matching). """ import os import re import sys from datetime import datetime, timedelta, timezone IST = timezone(timedelta(hours=5, minutes=30)) STAMP = os.environ['STAMP'] P1 = os.environ['P1'] P2 = os.environ['P2'] COMBO = os.environ['COMBO'] OUT_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'gen') os.makedirs(OUT_DIR, exist_ok=True) now = datetime.now(IST) # First delivery: next whole 2h boundary at least 2h out (keeps :00 minutes # out of the picture — minutes are wild, matched loosely by readback). base = (now + timedelta(hours=2)).replace(minute=0, second=0, microsecond=0) slots = [] for k in range(8): delivery = base + timedelta(hours=2 * k) freeze = delivery - timedelta(minutes=15) slots.append((delivery, freeze)) gen_hour = now.hour # 24h hour the wheels show when the flow starts def h12(h24): h = h24 % 12 return 12 if h == 0 else h def hour_walk(from24, to24): """Values to tap walking the 12h wheel UP from from24 to to24 (exclusive start).""" steps = (to24 - from24) % 24 out = [] h = from24 for _ in range(steps): h = (h + 1) % 24 out.append(str(h12(h))) return out def month_label(d): return d.strftime('%B %Y') # e.g. 'October 2026' (matches calendar title) def date_block(field, target, today): """YAML steps: open field date picker, navigate to target date, Done.""" nxt = (target.year - today.year) * 12 + (target.month - today.month) lines = [ f'- tapOn:\n id: {field}-date-picker', '- extendedWaitUntil:\n visible:\n text: Done\n timeout: 10000', '- waitForAnimationToEnd', # Compact date label, e.g. '4 Oct 2026'. "- tapOn:\n text: '[0-9]{1,2} [A-Za-z]+ [0-9]{4}'", '- waitForAnimationToEnd', ] if nxt > 0: lines += [ '- repeat:', f' times: {nxt}', ' commands:', ' - tapOn:\n id: DatePicker.NextMonth', ] lines += [ # Poll (not just assert): the calendar popover lives in its own window # and Maestro's animation detection doesn't cover it. '- extendedWaitUntil:', ' visible:', f" text: '{month_label(target)}'", ' timeout: 15000', f'- tapOn: \'{target.day}\'', # Tapping a day does NOT dismiss the calendar popover. Tap the compact # label (point tap: hierarchy hit-testing can't see it behind the # popover window) to toggle it shut — this also dismisses the modal # with the picked date committed (onChange fired on day tap). '- tapOn:', ' point: 55%,43%', # Done only if the calendar actually closed (month title gone). '- runFlow:', ' when:', ' visible:', ' text: Done', ' notVisible:', f" text: '{month_label(target)}'", ' commands:', ' - tapOn: Done', ] return lines def indented(steps, n): pad = ' ' * n return [pad + s.replace('\n', '\n' + pad) for s in steps] # IST clock in one JS expression (sim follows host clock; host is IST). IST_H = 'new Date(Date.now() + (330 + new Date().getTimezoneOffset()) * 60000).getHours()' IST_M = 'new Date(Date.now() + (330 + new Date().getTimezoneOffset()) * 60000).getMinutes()' def open_time(field): return [ f'- tapOn:\n id: {field}-time-picker', '- extendedWaitUntil:\n visible:\n text: Done\n timeout: 10000', '- waitForAnimationToEnd', ] def open_wheels(field): return open_time(field) + [ "- tapOn:\n text: '[0-9]{1,2}:[0-9]{2}.?[AP]M'", '- waitForAnimationToEnd', # Poll the wheels popover fully open (own window; Maestro's animation # detection doesn't cover it). Any selected hour matches (o.clock # dodges the YAML-hostile apostrophe in "o'clock"). '- extendedWaitUntil:', ' visible:', " text: '[0-9]{1,2} o.clock'", ' timeout: 15000', ] def close_wheels(): # Dismiss the wheels popover back to the modal, then close the modal. # Value already committed via onChange; nothing changed yet at this point. return [ '- tapOn:\n id: PopoverDismissRegion', '- waitForAnimationToEnd', '- tapOn: Done', '- waitForAnimationToEnd', ] def drag(x, y0, y1): return f'- swipe:\n start: {x}%,{y0:g}%\n end: {x}%,{y1:g}%\n duration: 300' # Row geometry (measured): hour col x=20% (up-drags from 58%), minute col # x=38%. Touch-down must be ON the selected row (~56%); starting above it # (e.g. 50%) dismisses the wheels without engaging. +N rows = upward drag; # -N = downward. Every drag closes the wheels modal with the value # committed, so each chunk reopens first. def up_drags(x, rows): return (x, 58, 58 - rows * 4.0) def down_drags(x, rows): return (x, 56, 56 + rows * 4.0) def chunk3_loop(prefix, field, x, rows_var, count_var, direction, rest_var): """3-row drag chunks. First chunk uses the already-open wheels (a value interaction closes them); remaining chunks reopen first.""" if direction > 0: dx, y0, y1 = up_drags(x, 3) cond = f'output.{prefix}_{rows_var} >= 3' else: dx, y0, y1 = down_drags(x, 3) cond = f'output.{prefix}_{rows_var} <= -3' first = [ f'- swipe:\n start: {dx}%,{y0:g}%\n end: {dx}%,{y1:g}%\n duration: 300', '- waitForAnimationToEnd', ] body = open_wheels(field) + [ f'- swipe:\n start: {dx}%,{y0:g}%\n end: {dx}%,{y1:g}%\n duration: 300', '- waitForAnimationToEnd', ] return [ '- runFlow:', ' when:', f' true: ${{{cond}}}', ' commands:', ] + indented(first, 6) + [ ' - runFlow:', ' when:', f' true: ${{output.{prefix}_{rest_var} >= 1}}', ' commands:', ' - repeat:', f' times: ${{output.{prefix}_{count_var}}}', ' commands:', ] + indented(body, 16) def remainder_branch(prefix, field, x, value, rows, rows_total_var, side=+1): """Conditional exact-rows drag. Wheels are open iff no chunk ran yet (total < 3 in magnitude), so the reopen prefix is itself conditional.""" if rows > 0: dx, y0, y1 = up_drags(x, rows) else: dx, y0, y1 = down_drags(x, -rows) drag = [ f'- swipe:\n start: {dx}%,{y0:g}%\n end: {dx}%,{y1:g}%\n duration: 300', '- waitForAnimationToEnd', ] if side > 0: ran, fresh = f'{rows_total_var} >= 3', f'{rows_total_var} < 3' else: ran, fresh = f'{rows_total_var} <= -3', f'{rows_total_var} > -3' return [ '- runFlow:', ' when:', f' true: ${{output.{prefix}_{value} == {rows}}}', ' commands:', # Chunks ran (modal closed) -> reopen first. ' - runFlow:', ' when:', f' true: ${{output.{prefix}_{ran}}}', ' commands:', ] + indented(open_wheels(field) + drag, 12) + [ # No chunks ran (wheels still open) -> drag directly. ' - runFlow:', ' when:', f' true: ${{output.{prefix}_{fresh}}}', ' commands:', ] + indented(drag, 12) def delivery_time(prefix, field, target_h24): o = prefix steps = open_wheels(field) + [ f'- evalScript: ${{output.{o}_H = {IST_H}}}', f'- evalScript: ${{output.{o}_M = {IST_M}}}', f'- evalScript: ${{output.{o}_hr = ({target_h24} - output.{o}_H + 48) % 24}}', f'- evalScript: ${{output.{o}_h3 = Math.floor(output.{o}_hr / 3)}}', f'- evalScript: ${{output.{o}_hrr = output.{o}_hr % 3}}', f'- evalScript: ${{output.{o}_h3r = output.{o}_h3 - 1}}', ] steps += chunk3_loop(prefix, field, 20, 'hr', 'h3r', +1, 'h3r') steps += remainder_branch(prefix, field, 20, 'hrr', 1, 'hr') steps += remainder_branch(prefix, field, 20, 'hrr', 2, 'hr') return steps def freeze_time(prefix, field, dmin_var, dh_target): o = prefix # Clock read BEFORE opening: the wheels init to ~now on open, so the # pre-open minute (M0) is the best estimate of the wheel init minute. # (Reading after the slow hour drags instead undershoots by elapsed min.) steps = [ f'- evalScript: ${{output.{o}_H = {IST_H}}}', f'- evalScript: ${{output.{o}_M0 = {IST_M}}}', # Freeze = delivery - 15min; delivery minute comes from the delivery # block's output var (dmin_var like output.s1d_M). f'- evalScript: ${{output.{o}_tm = ({dmin_var} - 15 + 60) % 60}}', f'- evalScript: ${{output.{o}_th = ({dh_target} - ({dmin_var}<15?1:0) + 24) % 24}}', f'- evalScript: ${{output.{o}_hr = (output.{o}_th - output.{o}_H + 48) % 24}}', f'- evalScript: ${{output.{o}_h3 = Math.floor(output.{o}_hr / 3)}}', f'- evalScript: ${{output.{o}_hrr = output.{o}_hr % 3}}', f'- evalScript: ${{output.{o}_h3r = output.{o}_h3 - 1}}', f'- evalScript: ${{output.{o}_mr0 = output.{o}_tm - output.{o}_M0}}', f'- evalScript: ${{output.{o}_mr = output.{o}_mr0>30?output.{o}_mr0-60:(output.{o}_mr0<-30?output.{o}_mr0+60:output.{o}_mr0)}}', f'- evalScript: ${{output.{o}_m3a = Math.floor(Math.abs(output.{o}_mr) / 3)}}', f'- evalScript: ${{output.{o}_m3r = output.{o}_m3a - 1}}', ] + open_wheels(field) steps += chunk3_loop(prefix, field, 20, 'hr', 'h3r', +1, 'h3r') steps += remainder_branch(prefix, field, 20, 'hrr', 1, 'hr') steps += remainder_branch(prefix, field, 20, 'hrr', 2, 'hr') # Minute wheel allows both directions (wraps); take the shorter way. # Minute wheel allows both directions (wraps); take the shorter way. steps += chunk3_loop(prefix, field, 38, 'mr', 'm3r', +1, 'm3r') steps += chunk3_loop(prefix, field, 38, 'mr', 'm3r', -1, 'm3r') steps += remainder_branch(prefix, field, 38, 'mrr', 1, 'mr') steps += remainder_branch(prefix, field, 38, 'mrr', 2, 'mr') steps += remainder_branch(prefix, field, 38, 'mrr', -1, 'mr', -1) steps += remainder_branch(prefix, field, 38, 'mrr', -2, 'mr', -1) return steps def slot_skus(idx): """Exact SKU sets per slot (ids from readback --skus; CBSK after combo). Every slot carries P1SK0+P2SK0 so both products' dialogs list all 8 slots in order; slot 1 additionally holds P1SK1+CBSK, slot 2 the rest of P2. """ e = os.environ base = [e['P1SK0'], e['P2SK0']] if idx == 1: return base + [e['P1SK1'], e['CBSK']] if idx == 2: return base + [e['P2SK1'], e['P2SK2'], e['P2SK3']] return base def slot_products(idx): """Attach exact SKU sets per slot (ids from readback --skus; CBSK after combo). No typing: rows expose testIDs but no label text, and search-box typing proved unreliable. Our SKUs sort last, so page to the bottom first with unconditional long swipes (overshoot-safe: the list pins at the end), then tap each SKU id exactly once, then Done (verified closed). """ e = os.environ skus = slot_skus(idx) lines = [ '- scrollUntilVisible:\n element:\n id: slot-products-selector\n direction: DOWN\n speed: 100\n visibilityPercentage: 60\n centerElement: true', '- waitForAnimationToEnd', '- tapOn:\n id: slot-products-selector', '- waitForAnimationToEnd', # The search box auto-focuses AFTER data loads (delayed) — the # keyboard then covers the swipe zone and paging silently no-ops. # Tap the sheet title to blur search + dismiss the keyboard first. # Never type: search typing proved unreliable. "- tapOn:\n text: 'Select Products'", '- waitForAnimationToEnd', # Page the raw list — our SKUs sort last. '- repeat:', ' times: 12', ' commands:', ' - swipe:', ' start: 50%,80%', ' end: 50%,30%', ' duration: 300', '- waitForAnimationToEnd', ] for sk in skus: lines += [ f'- tapOn:\n id: slot-products-selector-option-{sk}', '- waitForAnimationToEnd', ] lines += [ '- tapOn:\n id: slot-products-selector-done', '- extendedWaitUntil:', ' notVisible:', ' text: Select Products', ' timeout: 10000', ] return lines yaml = [ '# GENERATED by scripts/gen_slots.py — do not edit. Regenerated every run.', 'appId: ${APP_ID || "in.freshyo.adminui"}', 'env:', ' APP_ID: ${APP_ID || "in.freshyo.adminui"}', ' STAFF_NAME: ${STAFF_NAME || ""}', ' STAFF_PASSWORD: ${STAFF_PASSWORD || ""}', 'tags:', ' - full-suite', ' - slots', '---', '- launchApp', '- extendedWaitUntil:\n visible:\n id: \'login-name-input|add-product-menu-item\'\n timeout: 120000', # NOTE: path is relative to this generated file (gen/), not the workspace root. '- runFlow:\n when:\n visible:\n id: login-name-input\n commands:\n - runFlow: ../subflows/login.yaml', ] targets = [] today = now.date() # Subset retries: SLOT_FROM/SLOT_TO (default 1/8) emit only those legs, so a # failed run can resume without duplicating committed slots. The first # emitted leg always navigates via the dashboard menu. SLOT_FROM = int(os.environ.get('SLOT_FROM', '1')) SLOT_TO = int(os.environ.get('SLOT_TO', '8')) for idx, (delivery, freeze) in enumerate(slots, start=1): if idx < SLOT_FROM or idx > SLOT_TO: continue if idx == SLOT_FROM: yaml += [ f'# --- Slot {idx}: delivery {delivery} / freeze {freeze} ---', '- tapOn:\n id: delivery-slots-menu-item', '- extendedWaitUntil:\n visible:\n id: add-slot-fab\n timeout: 20000', ] else: # After each submit the app backs onto the slots list, so later # iterations go straight to the FAB (no dashboard menu in view). yaml += [ f'# --- Slot {idx}: delivery {delivery} / freeze {freeze} ---', '- extendedWaitUntil:\n visible:\n id: add-slot-fab\n timeout: 20000', ] yaml += [ '- tapOn:\n id: add-slot-fab', '- extendedWaitUntil:\n visible:\n id: delivery-date-picker\n timeout: 20000', ] yaml += date_block('delivery', delivery.date(), today) # Delivery: hour to target (minute accepted as-is, read back later). yaml += delivery_time(f's{idx}d', 'delivery', delivery.hour) yaml += date_block('freeze', freeze.date(), today) # Freeze = delivery - 15min; delivery minute is this slot's output var. yaml += freeze_time(f's{idx}f', 'freeze', f'output.s{idx}d_M', delivery.hour) # Products: exact SKU sets per slot (see slot_skus). yaml += slot_products(idx) yaml += [ '- scrollUntilVisible:\n element:\n id: create-slot-button\n direction: DOWN\n speed: 100\n visibilityPercentage: 60\n centerElement: true', '- waitForAnimationToEnd', '- tapOn:\n id: create-slot-button', "- assertVisible: 'Slot created successfully!'", '- tapOn: OK', ] targets.append( f'SLOT{idx}_DDATE={delivery.strftime("%Y-%m-%d")} SLOT{idx}_DHOUR={delivery.hour:02d} ' f'SLOT{idx}_FDATE={freeze.strftime("%Y-%m-%d")} SLOT{idx}_FHOUR={freeze.hour:02d}' ) def settle(text): pat = re.compile(r'(- scrollUntilVisible:\n(?: [^\n]+\n)+?)(?=- |\Z)') def rep(m): block = m.group(1) if 'waitForAnimationToEnd' in block: return block return block + '- waitForAnimationToEnd\n' return pat.sub(rep, text) with open(os.path.join(OUT_DIR, 'admin-slots.yaml'), 'w') as f: f.write(settle('\n'.join(yaml)) + '\n') if SLOT_FROM == 1 and SLOT_TO == 8: with open(os.path.join(OUT_DIR, 'slot-targets.env'), 'w') as f: f.write('\n'.join(targets) + '\n') else: print(f'subset run: slot-targets.env left untouched ({len(targets)} legs regen)') print(f'generated slots {SLOT_FROM}-{SLOT_TO}, first delivery {slots[SLOT_FROM - 1][0]}, last {slots[SLOT_TO - 1][0]}')