write_carried_facts.py

The Python program of A delivery note that knows its own order. Every line of the note carries the order it was picked for, the article code and the shelf it came off, and prints none of them. The place where the driver signs carries the round and the van, and a mark beside the fold tick carries nothing but its own place.

Python 364 lines
  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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""Draws a delivery note whose every line carries the order it came from, without
printing it.

The Python twin of the `write_carried_facts` example in Rust. A warehouse prints a note
for the driver and keeps a record for itself, and the two have to be paired up again
when the signed sheet comes back. Printing the codes on the note would pair them, at
the price of a column of machine words on a sheet a customer reads.

So the codes travel under the page instead. Each line of the note is drawn inside a
marked run, and the run points at a list of the caller's own facts held once in the
file; the point where the driver signs carries a list of its own. Nothing of any list
is drawn: a program reading the file afterwards finds every code against the line it
belongs to, and an eye reading the sheet finds a delivery note.

The library says nothing about what a list holds. The names and the values here are the
warehouse's own, and another trade would carry other ones.

The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The codes, the quantities and the shelves are the same in both.

Usage: python examples/write_carried_facts.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_carried_facts.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf


@dataclass(frozen=True)
class Carried:
    """What one line of the note carries under the page."""

    order: str
    article: str
    bin: str
    quantity: int


# What each line carries, in the order the note delivers them. A code is a code in every
# language, so these stay out of `Words`.
CARRIED = (
    Carried(order="SO-88412", article="TBL-OAK-180", bin="A-14-3", quantity=1),
    Carried(order="SO-88412", article="CHR-WAL-04", bin="A-09-1", quantity=6),
    Carried(order="SO-88451", article="SBD-3DR-120", bin="B-02-7", quantity=1),
    Carried(order="SO-88451", article="SHF-WAL-090", bin="C-31-2", quantity=4),
    Carried(order="SO-88463", article="CST-STD-01", bin="C-08-5", quantity=2),
    Carried(order="SO-88463", article="LMP-FLR-BRS", bin="D-17-9", quantity=3),
)

# The round the driver is on, carried by the point where the note is signed.
ROUND = "RT-2026-224"

# The van the round is driven in, carried by the same point.
VAN = "DRV-118"


@dataclass(frozen=True)
class Words:
    """Every word the note draws, in one language."""

    title: str
    lead: str
    note: str
    consignee: str
    goods: str
    count: str
    picked: str
    items: tuple[str, ...]
    signature: str
    beneath: str
    carried: str
    fold: str
    folded: str
    caveat: str


# The note in English.
ENGLISH = Words(
    title="A delivery note that knows which order it came from",
    lead=(
        "Every line of the note below carries the order it was picked for, the article "
        "code and the shelf it came off, and prints none of the three. The line is "
        "drawn inside a marked run, and the run points at a list of facts held once in "
        "the file under the warehouse's own names. The sheet that comes back signed is "
        "therefore paired with the records it came from by reading the file, not by "
        "reading the paper."
    ),
    note="The note the driver carries",
    consignee=(
        "Meunier & Filles, 14 rue des Tanneurs, Tours — delivered 13 August 2026"
    ),
    goods="Goods",
    count="Qty",
    picked="Picked by",
    items=(
        "Oak dining table, 180 cm",
        "Dining chair, walnut",
        "Sideboard, three doors",
        "Wall shelf, 90 cm",
        "Coat stand",
        "Floor lamp, brushed steel",
    ),
    signature="Signed on delivery",
    beneath="What travels under the page",
    carried=(
        "Seven lists of facts travel with this sheet: one against each of the six "
        "lines, and one at the point where the driver signs, which carries the round "
        "and the van. Not one letter of any of them is drawn. A list is written once "
        "in the file and pointed at from the page, so a list that belongs to several "
        "places is held once and marked as often as it is needed."
    ),
    fold="The mark that carries nothing",
    folded=(
        "The short stroke in the left margin is where the sheet is folded for a window "
        "envelope, and a mark of its own is put in the page beside it, under a name "
        "and with no facts at all. A place is sometimes all there is to say."
    ),
    caveat=(
        "What a list holds is the caller's business: an order number here, an article "
        "code in a catalogue, a state against a box on a form. The library neither "
        "reads these names nor acts on them — it writes them down and ties them to "
        "what was drawn."
    ),
)

# The note in French.
FRENCH = Words(
    title="Un bon de livraison qui sait de quelle commande il vient",
    lead=(
        "Chaque ligne du bon ci-dessous porte la commande pour laquelle elle a été "
        "préparée, le code de l'article et l'étagère d'où il sort, et n'imprime aucun "
        "des trois. La ligne est dessinée dans un repère, et ce repère désigne une "
        "liste de renseignements écrite une seule fois dans le fichier, sous les noms "
        "de l'entrepôt. La feuille qui revient signée se rapproche donc de ses "
        "enregistrements en lisant le fichier, et non en lisant le papier."
    ),
    note="Le bon que le chauffeur emporte",
    consignee="Meunier & Filles, 14 rue des Tanneurs, Tours — livré le 13 août 2026",
    goods="Marchandise",
    count="Qté",
    picked="Préparé par",
    items=(
        "Table de salle à manger en chêne, 180 cm",
        "Chaise de salle à manger en noyer",
        "Buffet trois portes",
        "Étagère murale, 90 cm",
        "Portemanteau",
        "Lampadaire en acier brossé",
    ),
    signature="Signature à la livraison",
    beneath="Ce qui voyage sous la page",
    carried=(
        "Sept listes de renseignements voyagent avec cette feuille : une contre "
        "chacune des six lignes, et une au point où le chauffeur signe, qui porte la "
        "tournée et le véhicule. Pas une lettre de l'une d'elles n'est dessinée. Une "
        "liste est écrite une fois puis désignée depuis la page : une liste qui vaut à "
        "plusieurs endroits n'est donc écrite qu'une fois et posée autant de fois "
        "qu'il le faut."
    ),
    fold="Le repère qui ne porte rien",
    folded=(
        "Le petit trait de la marge gauche est l'endroit où la feuille se plie pour "
        "une enveloppe à fenêtre, et un repère à lui est posé dans la page juste à "
        "côté, sous un nom et sans le moindre renseignement. Un endroit suffit parfois "
        "à tout dire."
    ),
    caveat=(
        "Ce qu'une liste porte appartient à l'appelant : un numéro de commande ici, "
        "une référence d'article dans un catalogue, un état contre une case d'un "
        "formulaire. La bibliothèque ne lit pas ces noms et n'en fait rien — elle les "
        "écrit et les attache à ce qui a été dessiné."
    ),
)

# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH}

# The left edge of everything on the page.
LEFT = 72.0

# How wide a block of text is.
WIDTH = 451.0

# How wide the column of goods is.
GOODS_WIDTH = 300.0

# Where the column of quantities begins, and how wide it is.
COUNT_AT = LEFT + GOODS_WIDTH
COUNT_WIDTH = 50.0

# Where the column naming the picker begins.
PICKED_AT = COUNT_AT + COUNT_WIDTH

# How far apart two lines of the note stand.
PITCH = 18.0

# The size the note is set at.
NOTE_SIZE = 9.5

# The grey the page draws its second-rank words in.
GREY = hqf_pdf.Rgb.gray(0.42)

# The grey the rules of the note are drawn in.
RULE = hqf_pdf.Rgb.gray(0.72)

# Who picked each line, which the note does print.
PICKERS = ("MJ", "MJ", "PL", "PL", "SD", "SD")


def block(
    content: hqf_pdf.Content,
    flow: hqf_pdf.TextFlow,
    x: float,
    top: float,
    width: float,
    text: str,
) -> float:
    """Sets a block of words at `top`, and hands back the ordinate it ends at."""
    lines = flow.break_lines(text, width)
    # The binding opens the text object itself, so opening another here would write a
    # pair of operators its twin in Rust does not.
    flow.draw(content, lines, x, top, width)
    return top - flow.height(lines)


def facts_of(line: Carried) -> dict[str, str]:
    """The list of facts one line of the note carries."""
    return {"Order": line.order, "Article": line.article, "Bin": line.bin}


def round_facts() -> dict[str, str]:
    """The list of facts the point where the note is signed carries."""
    return {"Round": ROUND, "Van": VAN}


def lines_of_the_note(
    content: hqf_pdf.Content,
    font: hqf_pdf.FontHandle,
    words: Words,
    lists: list[hqf_pdf.PropertiesHandle],
    top: float,
) -> float:
    """Draws the six lines of the note, each inside the run that carries its facts."""
    goods = hqf_pdf.TextFlow(font, NOTE_SIZE)
    figure = hqf_pdf.TextFlow(font, NOTE_SIZE, align=hqf_pdf.Align.Right)
    picker = hqf_pdf.TextFlow(font, NOTE_SIZE, align=hqf_pdf.Align.Right)

    row = top
    for index, line in enumerate(CARRIED):
        content.begin_marked_with("Line", lists[index])
        block(content, goods, LEFT, row, GOODS_WIDTH, words.items[index])
        block(content, figure, COUNT_AT, row, COUNT_WIDTH, str(line.quantity))
        block(content, picker, PICKED_AT, row, LEFT + WIDTH - PICKED_AT, PICKERS[index])
        content.end_marked()

        content.set_stroke(RULE)
        content.set_line_width(0.4)
        content.move_to(LEFT, row - PITCH + 4.0)
        content.line_to(LEFT + WIDTH, row - PITCH + 4.0)
        content.stroke()
        row -= PITCH
    return row


def build(document: hqf_pdf.Document, font: hqf_pdf.FontHandle, words: Words) -> None:
    """Draws the whole page."""
    lists = [document.add_properties(facts_of(line)) for line in CARRIED]
    round_list = document.add_properties(round_facts())

    title = hqf_pdf.TextFlow(font, 18.0)
    lead = hqf_pdf.TextFlow(font, 10.0)
    label = hqf_pdf.TextFlow(font, 12.0)
    small = hqf_pdf.TextFlow(font, 8.5, color=GREY)
    small_right = hqf_pdf.TextFlow(font, 8.5, align=hqf_pdf.Align.Right, color=GREY)

    content = hqf_pdf.Content()
    top = 790.0
    top = block(content, title, LEFT, top, WIDTH, words.title) - 12.0
    top = block(content, lead, LEFT, top, WIDTH, words.lead) - 22.0

    top = block(content, label, LEFT, top, WIDTH, words.note) - 10.0
    top = block(content, small, LEFT, top, WIDTH, words.consignee) - 12.0

    block(content, small, LEFT, top, GOODS_WIDTH, words.goods)
    block(content, small_right, COUNT_AT, top, COUNT_WIDTH, words.count)
    top = (
        block(
            content, small_right, PICKED_AT, top, LEFT + WIDTH - PICKED_AT, words.picked
        )
        - 4.0
    )

    content.set_stroke(hqf_pdf.Rgb.gray(0.3))
    content.set_line_width(0.6)
    content.move_to(LEFT, top)
    content.line_to(LEFT + WIDTH, top)
    content.stroke()

    top = lines_of_the_note(content, font, words, lists, top - 12.0) - 16.0

    # The point where the driver signs, and the list the round travels in.
    content.mark_point_with("Signature", round_list)
    content.set_stroke(hqf_pdf.Rgb.gray(0.3))
    content.set_line_width(0.5)
    content.move_to(LEFT + WIDTH - 200.0, top)
    content.line_to(LEFT + WIDTH, top)
    content.stroke()
    top = (
        block(content, small_right, LEFT + WIDTH - 200.0, top - 3.0, 200.0, words.signature)
        - 26.0
    )

    # The fold tick, and the mark that carries nothing but its own place.
    content.set_stroke(RULE)
    content.set_line_width(0.4)
    content.move_to(LEFT - 18.0, 561.0)
    content.line_to(LEFT - 8.0, 561.0)
    content.stroke()
    content.mark_point("Fold")

    top = block(content, label, LEFT, top, WIDTH, words.beneath) - 10.0
    top = block(content, lead, LEFT, top, WIDTH, words.carried) - 18.0
    top = block(content, label, LEFT, top, WIDTH, words.fold) - 10.0
    top = block(content, lead, LEFT, top, WIDTH, words.folded) - 20.0

    closing = hqf_pdf.TextFlow(font, 9.0, color=GREY)
    block(content, closing, LEFT, top, WIDTH, words.caveat)

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(
        Path(_language.file_name("carried_facts.pdf", language)).stem
    )

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    build(document, font, words)

    written = document.write(out)
    print(f"wrote {out}: {written} bytes, {len(CARRIED) + 1} lists carried and none drawn")


if __name__ == "__main__":
    main()