inventory.py (6815B)
1 # This file is part of GNU Taler 2 # (C) 2026 Taler Systems S.A. 3 # 4 # GNU Taler is free software; you can redistribute it and/or modify it under the 5 # terms of the GNU General Public License as published by the Free Software 6 # Foundation; either version 3, or (at your option) any later version. 7 # 8 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 9 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 10 # A PARTICULAR PURPOSE. See the GNU General Public License for more details. 11 # 12 # You should have received a copy of the GNU General Public License along with 13 # GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 14 """A catalogue on a *real* backend, arranged to stress the screens that show it. 15 16 The mock can answer anything, which is exactly why it cannot settle what the 17 order grid, the order-details page and the receipt do with a product that a 18 real merchant really sold: the mock's products are never bought, never 19 recorded in a contract and never read back out of an order. So this puts a 20 handful of deliberately awkward products on the demo instance and leaves them 21 there, named so that a passer-by can see where they came from: 22 23 possim-image carries a real PNG, to see whether anything renders it 24 possim-long-name a description no column is wide enough for 25 possim-kg sold by weight, so the quantity is fractional 26 possim-unicode a name in four scripts and an emoji 27 possim-cheap one cent, which is where per-unit arithmetic rounds 28 possim-free zero, which several screens treat as "no price" 29 30 They go in a category of their own ("POS simulator") so they can be found in 31 the grid without scrolling past the instance's own hundred-odd products, and 32 so that the category tab itself gets exercised. 33 34 python3 inventory.py show 35 python3 inventory.py ensure 36 python3 inventory.py remove 37 """ 38 39 from __future__ import annotations 40 41 import base64 42 import os 43 import struct 44 import sys 45 import zlib 46 from pathlib import Path 47 from typing import Optional 48 49 sys.path.insert(0, str(Path(__file__).resolve().parent)) 50 51 import merchant 52 53 CATEGORY = "POS simulator" 54 PREFIX = "possim-" 55 56 57 def _png(width: int, height: int, rgb: tuple[int, int, int]) -> bytes: 58 """A solid-colour PNG, built here rather than shipped as a binary blob. 59 60 `decodeProductImage` asks `BitmapFactory` for the real dimensions before 61 it decodes, so the image has to be a real one; a one-pixel placeholder 62 would not tell us what the grid does with an image that has a shape. 63 """ 64 raw = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height)) 65 66 def chunk(tag: bytes, data: bytes) -> bytes: 67 return (struct.pack(">I", len(data)) + tag + data 68 + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)) 69 70 header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) 71 return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) 72 + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")) 73 74 75 def data_url(width: int = 240, height: int = 240, 76 rgb: tuple[int, int, int] = (0x00, 0x42, 0xB3)) -> str: 77 """The `data:image/png;base64,...` shape the terminal accepts.""" 78 return "data:image/png;base64," + base64.b64encode( 79 _png(width, height, rgb)).decode() 80 81 82 # description, price (without the currency), unit, extra 83 SPEC: list[tuple[str, str, str, str, dict]] = [ 84 ("image", "Simulator tile with a picture", "2.50", "item", 85 {"image": data_url()}), 86 ("long-name", 87 "Simulator product with a deliberately long description that no column " 88 "on any of the terminal's screens is wide enough to show in one line, " 89 "written out at length so that the truncation can be seen", 90 "1.00", "item", {}), 91 ("kg", "Simulator loose goods", "4.00", "kg", {}), 92 ("unicode", "Café ☕ ことわざ Ωμέγα عربى", "3.00", "item", {}), 93 ("cheap", "Simulator one-cent item", "0.01", "item", {}), 94 ("free", "Simulator free sample", "0.00", "item", {}), 95 ] 96 97 98 def ensure(inst: Optional[merchant.Instance] = None) -> dict: 99 """Put the catalogue in place, and say what was already there. 100 101 Idempotent: a product that exists is left alone (the backend answers 409 102 and `add_product` accepts that), so this can be run before every round. 103 """ 104 inst = inst or merchant.demo() 105 token = inst.token.value 106 existing = {c["name"]: c["category_id"] for c in inst.merchant.categories(token)} 107 if CATEGORY in existing: 108 category_id = existing[CATEGORY] 109 else: 110 category_id = inst.merchant.add_category(token, CATEGORY) 111 have = {p["product_id"] for p in inst.merchant.products(token)} 112 added = [] 113 for suffix, description, price, unit, extra in SPEC: 114 product_id = PREFIX + suffix 115 if product_id in have: 116 continue 117 inst.merchant.add_product( 118 token, product_id, description, f"{inst.currency}:{price}", 119 total_stock=-1, unit=unit, 120 categories=[category_id] if category_id >= 0 else None, 121 extra=extra) 122 added.append(product_id) 123 return {"category": CATEGORY, "category_id": category_id, 124 "added": added, "already": sorted(have & {PREFIX + s[0] for s in SPEC})} 125 126 127 def remove(inst: Optional[merchant.Instance] = None) -> list[str]: 128 """Take them away again. A product in a past order cannot be deleted.""" 129 inst = inst or merchant.demo() 130 token = inst.token.value 131 gone = [] 132 for product in inst.merchant.products(token): 133 if product["product_id"].startswith(PREFIX): 134 inst.merchant.delete_product(token, product["product_id"]) 135 gone.append(product["product_id"]) 136 return gone 137 138 139 def show(inst: Optional[merchant.Instance] = None) -> None: 140 inst = inst or merchant.demo() 141 token = inst.token.value 142 print(f"{inst.label}: {inst.currency}") 143 for category in inst.merchant.categories(token): 144 print(f" category {category['category_id']}: {category['name']}") 145 # The list endpoint answers with summaries; the detail endpoint is where 146 # the price, the unit and the image actually are. 147 for entry in inst.merchant.products(token): 148 if not entry["product_id"].startswith(PREFIX): 149 continue 150 full = inst.merchant.product(token, entry["product_id"]) 151 image = full.get("image") or "" 152 print(f" {entry['product_id']:<20} {full.get('price')!r:<14} " 153 f"{full.get('unit')!r:<8} image={len(image):>6}B " 154 f"{str(full.get('description'))[:44]!r}") 155 156 157 if __name__ == "__main__": 158 want = sys.argv[1] if len(sys.argv) > 1 else "show" 159 if want == "ensure": 160 print(ensure()) 161 elif want == "remove": 162 print(remove()) 163 else: 164 show()