fillmate 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. fillmate/__init__.py +19 -0
  2. fillmate/__main__.py +3 -0
  3. fillmate/authoring.py +403 -0
  4. fillmate/cli.py +179 -0
  5. fillmate/engine.py +188 -0
  6. fillmate/examples/travel-request/pack.yaml +92 -0
  7. fillmate/examples/travel-request/travel_notice.docx +0 -0
  8. fillmate/examples/travel-request/travel_request.pdf +0 -0
  9. fillmate/fill_docx.py +100 -0
  10. fillmate/fill_pdf.py +81 -0
  11. fillmate/gui/__init__.py +0 -0
  12. fillmate/gui/app.py +1001 -0
  13. fillmate/gui/calibrate.py +738 -0
  14. fillmate/gui/common.py +232 -0
  15. fillmate/gui/fields.py +212 -0
  16. fillmate/gui/frame.py +558 -0
  17. fillmate/gui/ink.py +1867 -0
  18. fillmate/gui/settings.py +779 -0
  19. fillmate/mail/__init__.py +67 -0
  20. fillmate/mail/gmail.py +179 -0
  21. fillmate/mail/mailapp.py +30 -0
  22. fillmate/mail/senders.py +12 -0
  23. fillmate/mail/smtp.py +106 -0
  24. fillmate/pack.py +388 -0
  25. fillmate/paths.py +55 -0
  26. fillmate/resources/fillmate.svg +35 -0
  27. fillmate/resources/fonts/Archivo-Variable.ttf +0 -0
  28. fillmate/resources/fonts/Caveat-Variable.ttf +0 -0
  29. fillmate/resources/fonts/CourierPrime-Regular.ttf +0 -0
  30. fillmate/resources/fonts/Inter-Variable.ttf +0 -0
  31. fillmate/resources/fonts/OFL-Archivo.txt +93 -0
  32. fillmate/resources/fonts/OFL-Caveat.txt +93 -0
  33. fillmate/resources/fonts/OFL-CourierPrime.txt +93 -0
  34. fillmate/resources/fonts/OFL-Inter.txt +93 -0
  35. fillmate/resources/fonts/README.md +9 -0
  36. fillmate/store.py +94 -0
  37. fillmate/templating.py +81 -0
  38. fillmate-0.1.1.dist-info/METADATA +178 -0
  39. fillmate-0.1.1.dist-info/RECORD +42 -0
  40. fillmate-0.1.1.dist-info/WHEEL +4 -0
  41. fillmate-0.1.1.dist-info/entry_points.txt +5 -0
  42. fillmate-0.1.1.dist-info/licenses/LICENSE +21 -0
fillmate/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """fillmate: fill recurring paperwork from reusable form packs and send it by email."""
2
+
3
+ __version__ = "0.1.1"
4
+
5
+
6
+ class FillmateError(Exception):
7
+ """Base class for errors shown to the user as plain messages."""
8
+
9
+
10
+ class PackError(FillmateError):
11
+ """A form pack is malformed or one of its templates fails."""
12
+
13
+
14
+ class InputError(FillmateError):
15
+ """A value entered by the user is missing or invalid."""
16
+
17
+
18
+ class MailError(FillmateError):
19
+ """Sending or preparing an email failed."""
fillmate/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
fillmate/authoring.py ADDED
@@ -0,0 +1,403 @@
1
+ """Creating and editing packs from the app (calibration tool).
2
+
3
+ pack.yaml is edited with ruamel.yaml in round-trip mode so the author's comments and
4
+ layout survive. Every save is validated with load_pack and rolled back if it fails.
5
+ """
6
+ import io
7
+ import re
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ import pymupdf
12
+ from ruamel.yaml import YAML
13
+ from ruamel.yaml.comments import CommentedMap, CommentedSeq
14
+
15
+ from . import PackError
16
+ from .pack import ID_RE, NAME_RE, SPEC_FILE, load_pack
17
+ from .templating import slug
18
+
19
+
20
+ def _yaml():
21
+ y = YAML()
22
+ y.preserve_quotes = True
23
+ y.width = 4096 # keep each fill entry on one line
24
+ y.indent(mapping=2, sequence=4, offset=2)
25
+ return y
26
+
27
+
28
+ def read_spec(root):
29
+ return _yaml().load((Path(root) / SPEC_FILE).read_text(encoding="utf-8"))
30
+
31
+
32
+ def write_spec(root, spec):
33
+ """Write pack.yaml, validate it, and restore the previous version if it is invalid."""
34
+ path = Path(root) / SPEC_FILE
35
+ old = path.read_text(encoding="utf-8") if path.exists() else None
36
+ buf = io.StringIO()
37
+ _yaml().dump(spec, buf)
38
+ path.write_text(buf.getvalue(), encoding="utf-8")
39
+ try:
40
+ return load_pack(root)
41
+ except PackError:
42
+ if old is None:
43
+ path.unlink()
44
+ else:
45
+ path.write_text(old, encoding="utf-8")
46
+ raise
47
+
48
+
49
+ def _flow(items):
50
+ seq = CommentedSeq(items)
51
+ seq.fa.set_flow_style()
52
+ return seq
53
+
54
+
55
+ def _round(v):
56
+ v = round(float(v) * 2) / 2 # half-point steps are plenty precise
57
+ return int(v) if v == int(v) else v
58
+
59
+
60
+ def entry_to_yaml(entry):
61
+ """A fill entry as compact YAML: one line per entry, like a hand-written pack."""
62
+ m = CommentedMap()
63
+ if "field" in entry:
64
+ m["field"] = entry["field"]
65
+ m["value"] = entry["value"]
66
+ elif "mark" in entry:
67
+ m["mark"] = entry["mark"]
68
+ if entry.get("page", 0):
69
+ m["page"] = entry["page"]
70
+ m["at"] = _flow([_round(v) for v in entry["at"]])
71
+ if entry.get("symbol", "X") != "X":
72
+ m["symbol"] = entry["symbol"]
73
+ if float(entry.get("size", 11)) != 11:
74
+ m["size"] = _round(entry["size"])
75
+ else:
76
+ m["value"] = entry["value"]
77
+ if entry.get("page", 0):
78
+ m["page"] = entry["page"]
79
+ m["lines"] = _flow([_flow([_round(v) for v in line]) for line in entry["lines"]])
80
+ if float(entry.get("size", 10)) != 10:
81
+ m["size"] = _round(entry["size"])
82
+ if float(entry.get("min_size", 7)) != 7:
83
+ m["min_size"] = _round(entry["min_size"])
84
+ if entry.get("font", "helv") != "helv":
85
+ m["font"] = entry["font"]
86
+ m.fa.set_flow_style()
87
+ return m
88
+
89
+
90
+ def set_document_fill(root, doc_id, entries):
91
+ spec = read_spec(root)
92
+ for doc in spec.get("documents") or []:
93
+ if doc.get("id") == doc_id:
94
+ doc["fill"] = CommentedSeq(entry_to_yaml(e) for e in entries)
95
+ return write_spec(root, spec)
96
+ raise PackError(f"No document '{doc_id}' in the pack.")
97
+
98
+
99
+ def save_positions(root, doc_id, entries, new_fields=()):
100
+ """Save a document's fill entries together with the fields created while placing them.
101
+
102
+ One write: nothing reaches pack.yaml until the person saves, so leaving the editor
103
+ without saving never leaves half-made fields behind.
104
+ """
105
+ spec = read_spec(root)
106
+ existing = {f.get("id") for sec in ("profile", "fields") for f in spec.get(sec) or []}
107
+ for nf in new_fields:
108
+ if nf["id"] in existing:
109
+ continue
110
+ if not NAME_RE.match(nf["id"]):
111
+ raise PackError(f"'{nf['id']}' cannot be used as a field id.")
112
+ section = nf.get("section", "fields")
113
+ if spec.get(section) is None:
114
+ spec[section] = CommentedSeq()
115
+ m = CommentedMap(id=nf["id"], label=nf["label"])
116
+ if nf.get("type", "text") != "text":
117
+ m["type"] = nf["type"]
118
+ if nf.get("options"):
119
+ m["options"] = _flow(list(nf["options"]))
120
+ m.fa.set_flow_style()
121
+ spec[section].append(m)
122
+ existing.add(nf["id"])
123
+ for doc in spec.get("documents") or []:
124
+ if doc.get("id") == doc_id:
125
+ doc["fill"] = CommentedSeq(entry_to_yaml(e) for e in entries)
126
+ return write_spec(root, spec)
127
+ raise PackError(f"No document '{doc_id}' in the pack.")
128
+
129
+
130
+ def field_uses(root, field_id):
131
+ """Where pack.yaml mentions a field, other than its own definition (empty = unused)."""
132
+ spec = read_spec(root)
133
+ word = re.compile(rf"\b{re.escape(field_id)}\b")
134
+ places = []
135
+ for key, value in spec.items():
136
+ if key in ("profile", "fields"):
137
+ continue
138
+ buf = io.StringIO()
139
+ _yaml().dump({key: value}, buf)
140
+ if word.search(buf.getvalue()):
141
+ places.append(key)
142
+ return places
143
+
144
+
145
+ def remove_field(root, field_id):
146
+ """Delete a field nothing uses (made by mistake, or no longer needed)."""
147
+ places = field_uses(root, field_id)
148
+ if places:
149
+ raise PackError(f"'{field_id}' is still used in: {', '.join(places)}.")
150
+ spec = read_spec(root)
151
+ for sec in ("profile", "fields"):
152
+ items = spec.get(sec) or []
153
+ for i, f in enumerate(items):
154
+ if f.get("id") == field_id:
155
+ del items[i]
156
+ return write_spec(root, spec)
157
+ raise PackError(f"No field '{field_id}' in the pack.")
158
+
159
+
160
+ def add_field(root, field_id, label, field_type="text", section="fields"):
161
+ if not NAME_RE.match(field_id):
162
+ raise PackError("A field id uses letters, digits and _, and does not start with a digit.")
163
+ spec = read_spec(root)
164
+ for sec in ("profile", "fields"):
165
+ if any(f.get("id") == field_id for f in spec.get(sec) or []):
166
+ raise PackError(f"A field '{field_id}' already exists.")
167
+ if spec.get(section) is None:
168
+ spec[section] = CommentedSeq()
169
+ m = CommentedMap(id=field_id, label=label)
170
+ if field_type != "text":
171
+ m["type"] = field_type
172
+ m.fa.set_flow_style()
173
+ spec[section].append(m)
174
+ return write_spec(root, spec)
175
+
176
+
177
+ # --- new pack from a PDF -------------------------------------------------
178
+
179
+ def pdf_form_fields(path):
180
+ """(name, type) of the fillable fields of a PDF, in page order, without duplicates."""
181
+ out, seen = [], set()
182
+ with pymupdf.open(path) as pdf:
183
+ for page in pdf:
184
+ for w in page.widgets() or []:
185
+ if w.field_name and w.field_name not in seen:
186
+ seen.add(w.field_name)
187
+ kind = "bool" if w.field_type == pymupdf.PDF_WIDGET_TYPE_CHECKBOX else "text"
188
+ out.append((w.field_name, kind))
189
+ return out
190
+
191
+
192
+ def _field_id(name, used):
193
+ base = re.sub(r"\W+", "_", slug(name, 40)).strip("_").lower() or "field"
194
+ if base[0].isdigit():
195
+ base = "f_" + base
196
+ fid, n = base, 2
197
+ while fid in used:
198
+ fid, n = f"{base}_{n}", n + 1
199
+ used.add(fid)
200
+ return fid
201
+
202
+
203
+ def _new_pack_root(packs_dir, name):
204
+ packs_dir = Path(packs_dir)
205
+ pack_id = slug(name, 40).lower().replace("_", "-").strip("-") or "my-pack"
206
+ if not ID_RE.match(pack_id):
207
+ pack_id = "pack-" + pack_id
208
+ root, n = packs_dir / pack_id, 2
209
+ while root.exists():
210
+ root, n = packs_dir / f"{pack_id}-{n}", n + 1
211
+ root.mkdir(parents=True)
212
+ return root
213
+
214
+
215
+ def _skeleton(root, name, fields, doc):
216
+ spec = CommentedMap()
217
+ spec["fillmate"] = 1
218
+ spec["id"] = root.name
219
+ spec["name"] = name
220
+ spec["version"] = "1.0"
221
+ spec["description"] = ""
222
+ spec["date_format"] = "%d/%m/%Y"
223
+ spec["profile"] = CommentedSeq()
224
+ spec["fields"] = fields
225
+ spec["documents"] = CommentedSeq([doc])
226
+ spec["email"] = CommentedMap(to=CommentedSeq(), subject=name, body="Hello,\n\nplease find the document attached.\n")
227
+ return spec
228
+
229
+
230
+ def _label_for(name):
231
+ return name.replace("_", " ").strip().capitalize() or name
232
+
233
+
234
+ def docx_placeholders(path, pack=None):
235
+ """Names used as {{ placeholders }} in a Word document, minus fillmate's own helpers."""
236
+ from docxtpl import DocxTemplate
237
+
238
+ from .templating import make_env
239
+
240
+ env = make_env(pack)
241
+ try:
242
+ names = DocxTemplate(str(path)).get_undeclared_template_variables(jinja_env=env)
243
+ except Exception as e:
244
+ raise PackError(f"{Path(path).name}: a placeholder is not written correctly ({e}).") from e
245
+ return sorted(n for n in names if n not in env.globals)
246
+
247
+
248
+ def create_pack_from_docx(docx_path, packs_dir, name):
249
+ """Make a new pack folder around a Word document. Each {{ placeholder }} in it becomes a field."""
250
+ docx_path = Path(docx_path)
251
+ root = _new_pack_root(packs_dir, name)
252
+ template = "document.docx"
253
+ shutil.copy(docx_path, root / template)
254
+ fields = CommentedSeq()
255
+ try:
256
+ for ph in docx_placeholders(root / template):
257
+ if NAME_RE.match(ph):
258
+ f = CommentedMap(id=ph, label=_label_for(ph))
259
+ f.fa.set_flow_style()
260
+ fields.append(f)
261
+ doc = CommentedMap(id="document", label=docx_path.stem, template=template,
262
+ output=f"{docx_path.stem}_filled", placeholders=True)
263
+ return write_spec(root, _skeleton(root, name, fields, doc))
264
+ except PackError:
265
+ shutil.rmtree(root, ignore_errors=True)
266
+ raise
267
+
268
+
269
+ def sync_docx_fields(root):
270
+ """Add a field for every new {{ placeholder }} typed into the pack's Word documents.
271
+
272
+ Returns the reloaded pack, or None when nothing changed.
273
+ """
274
+ pack = load_pack(root)
275
+ known = {f.id for f in pack.profile + pack.fields} | set(pack.computed)
276
+ new = []
277
+ for d in pack.documents:
278
+ if d.kind == "docx" and d.placeholders:
279
+ for ph in docx_placeholders(d.template, pack):
280
+ if ph not in known and NAME_RE.match(ph):
281
+ known.add(ph)
282
+ new.append(ph)
283
+ if not new:
284
+ return None
285
+ spec = read_spec(root)
286
+ if spec.get("fields") is None:
287
+ spec["fields"] = CommentedSeq()
288
+ for ph in new:
289
+ f = CommentedMap(id=ph, label=_label_for(ph))
290
+ f.fa.set_flow_style()
291
+ spec["fields"].append(f)
292
+ return write_spec(root, spec)
293
+
294
+
295
+ def add_document(root, path):
296
+ """Copy a PDF or Word document into a pack as one more document to fill."""
297
+ root, path = Path(root), Path(path)
298
+ kind = path.suffix.lower()
299
+ if kind not in (".pdf", ".docx"):
300
+ raise PackError("Add a PDF or a Word (.docx) document.")
301
+ spec = read_spec(root)
302
+ docs = spec.get("documents") or CommentedSeq()
303
+ ids = {d.get("id") for d in docs}
304
+ templates = {d.get("template") for d in docs}
305
+ stem = re.sub(r"[^A-Za-z0-9_-]+", "_", path.stem).strip("_").lower() or "document"
306
+ doc_id, n = stem, 2
307
+ while doc_id in ids or not ID_RE.match(doc_id):
308
+ doc_id, n = f"{stem}-{n}" if ID_RE.match(stem) else f"document-{n}", n + 1
309
+ name, n = f"{stem}{kind}", 2
310
+ while name in templates or (root / name).exists():
311
+ name, n = f"{stem}_{n}{kind}", n + 1
312
+ shutil.copy(path, root / name)
313
+ doc = CommentedMap(id=doc_id, label=path.stem, template=name, output=f"{path.stem}_filled")
314
+ if kind == ".docx":
315
+ doc["placeholders"] = True
316
+ docs.append(doc)
317
+ spec["documents"] = docs
318
+ try:
319
+ pack = write_spec(root, spec)
320
+ except PackError:
321
+ (root / name).unlink(missing_ok=True)
322
+ raise
323
+ return sync_docx_fields(root) or pack if kind == ".docx" else pack
324
+
325
+
326
+ def remove_document(root, doc_id):
327
+ """Take a document out of a pack and delete its template file (unless another document uses it)."""
328
+ root = Path(root)
329
+ spec = read_spec(root)
330
+ docs = spec.get("documents") or []
331
+ if len(docs) <= 1:
332
+ raise PackError("A pack needs at least one document. Remove the whole pack instead.")
333
+ for i, d in enumerate(docs):
334
+ if d.get("id") == doc_id:
335
+ template = d.get("template")
336
+ del docs[i]
337
+ pack = write_spec(root, spec)
338
+ if template and all(x.get("template") != template for x in docs):
339
+ target = (root / template).resolve()
340
+ if target.parent == root.resolve() and target.is_file():
341
+ target.unlink()
342
+ return pack
343
+ raise PackError(f"No document '{doc_id}' in the pack.")
344
+
345
+
346
+ def create_pack_from_pdf(pdf_path, packs_dir, name):
347
+ """Make a new pack folder around a PDF. Fillable fields become pack fields automatically."""
348
+ pdf_path = Path(pdf_path)
349
+ root = _new_pack_root(packs_dir, name)
350
+ template = "form.pdf"
351
+ shutil.copy(pdf_path, root / template)
352
+
353
+ used, fields, fill = set(), CommentedSeq(), CommentedSeq()
354
+ for wname, kind in pdf_form_fields(root / template):
355
+ fid = _field_id(wname, used)
356
+ f = CommentedMap(id=fid, label=wname)
357
+ if kind == "bool":
358
+ f["type"] = "bool"
359
+ f.fa.set_flow_style()
360
+ fields.append(f)
361
+ fill.append(entry_to_yaml({"field": wname, "value": f"{{{{ {fid} }}}}"}))
362
+
363
+ doc = CommentedMap(id="form", label=pdf_path.stem, template=template, output=f"{pdf_path.stem}_filled", fill=fill)
364
+ try:
365
+ return write_spec(root, _skeleton(root, name, fields, doc))
366
+ except PackError:
367
+ shutil.rmtree(root, ignore_errors=True)
368
+ raise
369
+
370
+
371
+ # --- sample rendering ------------------------------------------------------
372
+
373
+ TAG_RE = re.compile(r"\{\{(.*?)\}\}")
374
+ BLOCK_RE = re.compile(r"\{%.*?%\}")
375
+
376
+
377
+ def sample_text(template, labels):
378
+ """Readable stand-in for a value template: {{ full_name }} -> "Full name"."""
379
+ def repl(m):
380
+ ident = re.match(r"\s*([A-Za-z_]\w*)", m.group(1))
381
+ return labels.get(ident.group(1), ident.group(1)) if ident else "…"
382
+ return BLOCK_RE.sub("", TAG_RE.sub(repl, template)).strip() or "Sample"
383
+
384
+
385
+ def render_page(pdf_path, page_no, dpi, entries=(), labels=None):
386
+ """PNG of one page; with entries, sample values are drawn so the layout can be checked."""
387
+ from .fill_pdf import put_text
388
+
389
+ with pymupdf.open(pdf_path) as pdf:
390
+ page = pdf[page_no]
391
+ for e in entries:
392
+ if e.get("page", 0) != page_no or "field" in e:
393
+ continue
394
+ if "mark" in e:
395
+ page.insert_text(e["at"], e.get("symbol", "X"), fontname="helv", fontsize=e.get("size", 11),
396
+ color=(0.1, 0.35, 0.9))
397
+ else:
398
+ full = {"font": "helv", "size": 10.0, "min_size": 7.0, **e}
399
+ try:
400
+ put_text(page, full, sample_text(e["value"], labels or {}), "sample")
401
+ except Exception:
402
+ pass # too long for the area: the editor flags it separately
403
+ return page.get_pixmap(dpi=dpi).tobytes("png"), len(pdf)
fillmate/cli.py ADDED
@@ -0,0 +1,179 @@
1
+ """Command line interface. Run `fillmate` with no arguments to open the desktop app."""
2
+ import argparse
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ from . import FillmateError, __version__, engine, mail, store
7
+ from .fill_docx import docx_to_pdf
8
+ from .mail.mailapp import open_draft
9
+ from .mail.senders import make_sender
10
+ from .pack import export_pack, import_pack, list_packs, load_pack
11
+ from .paths import examples_dir
12
+
13
+
14
+ def _find_pack(pack_id, settings):
15
+ packs, _ = list_packs(store.packs_dir(settings))
16
+ for p in packs:
17
+ if p.id == pack_id:
18
+ return p
19
+ candidate = Path(pack_id)
20
+ if (candidate / "pack.yaml").is_file():
21
+ return load_pack(candidate)
22
+ raise FillmateError(f"No installed pack '{pack_id}'. See `fillmate packs`.")
23
+
24
+
25
+ def _pairs(items, what):
26
+ out = {}
27
+ for item in items or []:
28
+ if "=" not in item:
29
+ raise FillmateError(f"{what} must look like key=value, got {item!r}.")
30
+ key, value = item.split("=", 1)
31
+ out[key.strip()] = value
32
+ return out
33
+
34
+
35
+ def cmd_packs(args, settings):
36
+ packs, problems = list_packs(store.packs_dir(settings))
37
+ print(f"Packs folder: {store.packs_dir(settings)}")
38
+ if not packs and not problems:
39
+ print("No packs installed. Try: fillmate install-example")
40
+ for p in packs:
41
+ print(f" {p.id:<24} {p.name} (v{p.version}, {len(p.documents)} documents)")
42
+ for folder, error in problems:
43
+ print(f" ! {folder.name}: {error}")
44
+
45
+
46
+ def cmd_fields(args, settings):
47
+ pack = _find_pack(args.pack, settings)
48
+ profile = store.load_profile()
49
+ print(f"{pack.name}\n\nProfile (fillmate profile --set id=value):")
50
+ for f in pack.profile:
51
+ mark = "*" if f.required else " "
52
+ print(f" {mark}{f.id:<22} {f.label} = {profile.get(f.id, '')!r}")
53
+ print("\nFields (fillmate fill --set id=value):")
54
+ for f in pack.fields:
55
+ mark = "*" if f.required else " "
56
+ extra = f" [{', '.join(f.options)}]" if f.options else ""
57
+ default = f" default: {f.default}" if f.default not in (None, "") else ""
58
+ print(f" {mark}{f.id:<22} {f.type:<9} {f.label}{extra}{default}")
59
+ presets = {**pack.presets, **store.load_user_presets(pack.id)}
60
+ if presets:
61
+ print(f"\nPresets (--preset): {', '.join(presets)}")
62
+
63
+
64
+ def cmd_profile(args, settings):
65
+ profile = store.load_profile()
66
+ if args.set:
67
+ profile.update(_pairs(args.set, "--set"))
68
+ store.save_profile(profile)
69
+ for key, value in profile.items():
70
+ print(f"{key}: {value}")
71
+
72
+
73
+ def cmd_fill(args, settings):
74
+ pack = _find_pack(args.pack, settings)
75
+ presets = {**pack.presets, **store.load_user_presets(pack.id)}
76
+ preset = None
77
+ if args.preset:
78
+ if args.preset not in presets:
79
+ raise FillmateError(f"Unknown preset '{args.preset}'. Available: {', '.join(presets) or 'none'}.")
80
+ preset = presets[args.preset]
81
+ ctx = engine.build_context(pack, store.load_profile(), _pairs(args.set, "--set"), preset)
82
+ for w in ctx.warnings:
83
+ print(f"WARNING: {w}", file=sys.stderr)
84
+ out = args.out or engine.output_folder(ctx, store.output_dir(settings))
85
+ outputs = engine.generate(ctx, out)
86
+ attachments = [o.path for o in outputs]
87
+ if args.docx_pdf:
88
+ attachments += [docx_to_pdf(o.path) for o in outputs if o.kind == "docx"]
89
+ for path in attachments:
90
+ print(f"created: {path}")
91
+ if args.no_mail:
92
+ return
93
+
94
+ test_mode, allowed = settings["test_mode"], settings["test_recipients"]
95
+ if test_mode:
96
+ print("TEST MODE: recipients replaced by the test recipients.")
97
+ d = engine.draft_email(ctx, test_mode, allowed)
98
+ sender = make_sender(settings)
99
+ msg = mail.build_message(sender.from_address() if sender else None,
100
+ d["to"], d["cc"], d["bcc"], d["subject"], d["body"], attachments)
101
+ eml = mail.write_draft(msg, Path(out) / "email.eml")
102
+ print(f"draft: {eml} (to: {', '.join(d['to']) or '-'})")
103
+ if args.open_draft:
104
+ open_draft(eml, d, attachments)
105
+ if args.send:
106
+ if sender is None:
107
+ raise FillmateError("Sending is set to 'mail app' in Settings: use --open-draft instead.")
108
+ ok, why = sender.ready()
109
+ if not ok:
110
+ raise FillmateError(f"Cannot send: {why}. Set it up in the app's Settings → Email.")
111
+ mail.send(sender, d["to"], d["cc"], d["bcc"], d["subject"], d["body"], attachments, test_mode, allowed)
112
+ print(f"sent to: {', '.join(d['to'] + d['cc'] + d['bcc'])}")
113
+
114
+
115
+ def cmd_import(args, settings):
116
+ pack = import_pack(args.path, store.packs_dir(settings), replace=args.replace)
117
+ print(f"installed: {pack.id} ({pack.name}) in {pack.root}")
118
+
119
+
120
+ def cmd_export(args, settings):
121
+ pack = _find_pack(args.pack, settings)
122
+ print(f"exported: {export_pack(pack, args.dest)}")
123
+
124
+
125
+ def cmd_install_example(args, settings):
126
+ for folder in sorted(examples_dir().iterdir()):
127
+ if (folder / "pack.yaml").is_file():
128
+ pack = import_pack(folder, store.packs_dir(settings), replace=True)
129
+ print(f"installed: {pack.id}")
130
+
131
+
132
+ def build_parser():
133
+ ap = argparse.ArgumentParser(prog="fillmate", description="Fill recurring paperwork from form packs.")
134
+ ap.add_argument("--version", action="version", version=f"fillmate {__version__}")
135
+ sub = ap.add_subparsers(dest="cmd")
136
+ sub.add_parser("gui", help="open the desktop app (default)")
137
+ sub.add_parser("packs", help="list installed packs")
138
+ p = sub.add_parser("fields", help="show a pack's profile fields, fields and presets")
139
+ p.add_argument("pack")
140
+ p = sub.add_parser("profile", help="show or set profile values")
141
+ p.add_argument("--set", action="append", metavar="ID=VALUE")
142
+ p = sub.add_parser("fill", help="fill a pack's documents and optionally email them")
143
+ p.add_argument("pack", help="pack id (or path to a pack folder)")
144
+ p.add_argument("--preset")
145
+ p.add_argument("--set", action="append", metavar="ID=VALUE",
146
+ help="field value; dates fields take a comma-separated list")
147
+ p.add_argument("--out", type=Path, help="output folder")
148
+ p.add_argument("--docx-pdf", action="store_true", help="also attach DOCX documents converted to PDF")
149
+ mode = p.add_mutually_exclusive_group()
150
+ mode.add_argument("--no-mail", action="store_true", help="only create the documents")
151
+ mode.add_argument("--open-draft", action="store_true", help="open the email in your mail app")
152
+ mode.add_argument("--send", action="store_true", help="send with the sender configured in Settings")
153
+ p = sub.add_parser("import", help="install a pack from a folder or .zip")
154
+ p.add_argument("path", type=Path)
155
+ p.add_argument("--replace", action="store_true", help="replace an installed pack with the same id")
156
+ p = sub.add_parser("export", help="zip an installed pack to share it (no personal data)")
157
+ p.add_argument("pack")
158
+ p.add_argument("dest", type=Path)
159
+ sub.add_parser("install-example", help="install the bundled example pack")
160
+ return ap
161
+
162
+
163
+ COMMANDS = {"packs": cmd_packs, "fields": cmd_fields, "profile": cmd_profile, "fill": cmd_fill,
164
+ "import": cmd_import, "export": cmd_export, "install-example": cmd_install_example}
165
+
166
+
167
+ def main(argv=None):
168
+ args = build_parser().parse_args(argv)
169
+ if args.cmd in (None, "gui"):
170
+ from .gui.app import main as gui_main
171
+ return gui_main()
172
+ try:
173
+ COMMANDS[args.cmd](args, store.load_settings())
174
+ except FillmateError as e:
175
+ sys.exit(f"error: {e}")
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()