-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreceipt.py
More file actions
195 lines (149 loc) · 5.34 KB
/
Copy pathreceipt.py
File metadata and controls
195 lines (149 loc) · 5.34 KB
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
"""Receipt composers.
`build_receipt` is the shared receipt template — every receipt type
goes through it. Specific receipts (`render_receipt`, `render_list`) choose
their banner text, items, totals, footer notes and optional upside-down joke.
"""
import logging
import random
import re
from blocks import (
Banner, Barcode, Block, Checkbox, Divider, Footer, Item, Spacer,
Total, Underline, UpsideDown,
)
from printer import print_blocks
from providers import item_providers, joke
logger = logging.getLogger(__name__)
# ── Shared defaults ──────────────────────────────────────────────────────────
DEFAULT_THANKS = "thank you for your vibes"
DEFAULT_FOOTER = "COME BACK SOON"
DEFAULT_BARCODE = "creativereceipt"
TAX_PERCENT = 13
RANDOM_THANKS = [
"congrats, you made a list",
"so many tasks",
"thanks for writing this down",
"tasks are fake, just vibes",
]
RANDOM_FOOTER = [
"NOW IGNORE IT",
"GOOD LUCK LOL",
"MAYBE TOMORROW",
"DOUBT EVERYTHING",
"THAT'S ENOUGH FOR TODAY",
]
TITLE_VARIANTS = [
"MAYBE DO",
"TASKS? LOL",
"PROCRASTINATION LIST",
"WELL...",
"IF I FEEL LIKE IT",
]
_NUM_RE = re.compile(r"[-+]?\d+(?:\.\d+)?")
def _extract_number(s: str) -> float | None:
cleaned = s.replace("\xa0", "").replace(" ", "")
m = _NUM_RE.search(cleaned)
return float(m.group()) if m else None
def _fmt_money(n: float) -> str:
return f"{n:,.2f}".replace(",", " ")
def _fetch_items(module) -> list[Item]:
try:
blocks = module.fetch() or []
except Exception as e:
logger.warning(f"Provider {module.__name__} failed: {e}")
return []
items = [b for b in blocks if isinstance(b, Item)]
if len(items) != len(blocks):
logger.warning(
f"Provider {module.__name__} returned {len(blocks) - len(items)} "
"non-Item block(s) — providers return Items only; ignored."
)
return items
def _joke() -> str | None:
"""Fetch one joke for the upside-down footer. None on failure."""
try:
return joke.fetch()
except Exception as e:
logger.warning(f"joke fetch failed: {e}")
return None
# ── Shared template ──────────────────────────────────────────────────────────
def build_receipt(
*,
banner_text: str,
items: list[Block],
totals: list[Block] | None = None,
column_header: tuple[str, str] | None = ("ITEM", "VALUE"),
upside_down: str | None = None,
thanks: str = DEFAULT_THANKS,
footer: str = DEFAULT_FOOTER,
barcode_text: str | None = DEFAULT_BARCODE,
) -> list[Block]:
"""Compose a receipt in the standard order.
Use `column_header=None` for receipts without an item/value column header
(e.g. plain checklists). Pass `barcode_text=None` to skip the footer barcode.
"""
out: list[Block] = []
out.append(Banner(banner_text))
out.append(Spacer())
if items:
if column_header:
out.append(Item(column_header[0], column_header[1], bold=True))
out.append(Divider("dash"))
out.extend(items)
out.append(Divider("dash"))
if totals:
out.extend(totals)
out.append(Spacer())
out.append(Underline(thanks))
out.append(Spacer())
if upside_down:
out.append(UpsideDown(upside_down))
out.append(Spacer())
out.append(Footer(footer))
if barcode_text:
out.append(Spacer())
out.append(Barcode(barcode_text))
out.append(Divider("dash"))
return out
# ── Default receipt: auto-discovered item providers + joke ──────────────────
def render_receipt() -> list[Block]:
all_items: list[Item] = []
for module in item_providers():
all_items += _fetch_items(module)
totals: list[Block] = []
if all_items:
subtotal = sum(
n for n in (_extract_number(it.value) for it in all_items) if n is not None
)
tax = subtotal * TAX_PERCENT / 100
grand = subtotal + tax
totals = [
Total("SUBTOTAL", _fmt_money(subtotal)),
Total(f"HST ({TAX_PERCENT}%)", _fmt_money(tax)),
Total("TOTAL", f"{_fmt_money(grand)} ₽", big=True),
]
return build_receipt(
banner_text="TODAY ONLY: 0% OFF EVERYTHING",
items=all_items,
totals=totals,
upside_down=_joke(),
)
def print_receipt() -> None:
print_blocks(render_receipt())
# ── Shopping / to-do list receipt: checkboxes only ──────────────────────────
def render_list(items: list[str]) -> list[Block]:
"""A checklist receipt: '[ ] item' rows with a count total."""
if not items:
return []
return build_receipt(
banner_text=random.choice(TITLE_VARIANTS),
items=[Checkbox(t) for t in items],
totals=[Total("ITEMS", str(len(items)), big=True)],
column_header=None,
upside_down=_joke(),
thanks=random.choice(RANDOM_THANKS),
footer=random.choice(RANDOM_FOOTER),
)
def print_list(items: list[str]) -> None:
blocks = render_list(items)
if blocks:
print_blocks(blocks)