diff --git a/README.md b/README.md
index 6169be4..74b3b60 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@ Printerface is an application that acts as a virtual printer, accepting LPD (Lin
The service is written in Python, with a Javascript web front end using bootstrap JS. It has a rich JSON API and can be used as a centralised interface to legacy system output, whereby documents can be parsed and then consumed by downstream services. We have production instances with over 100k documents a year, 5-6M pages.
-Computer systems as old as Windows NT4 can print to LPD printers as standard, so integration even into the most challenging environments is relatively easy compared to modifying legacy systems. Printerface provides a great path forward for customers trapped with old fixed-width, fanfold or pre-printed stationary systems, or struggling to maintain old dot-matrix line printers.
+Computer systems as old as Windows NT4 can print to LPD printers as standard, so integration even into the most challenging environments is relatively easy compared to modifying legacy systems. Printerface provides a great path forward for customers trapped with old fixed-width, fanfold or pre-printed stationery systems, or struggling to maintain old dot-matrix line printers.
Often we can de-duplicate or drop entirely sections of the documents that are no longer required in hard copies, to reduce the environmental footprint of legacy print jobs.
@@ -26,7 +26,7 @@ The following will checkout the source code, build a docker image and start an i
* `httpserver.py` the web server: path handlers and static files on aiohttp, handlers run on the event loop one at a time
* `mailer.py` asynchronous mail queue to Gmail
* `docparser` recognise and parse some plain-text formats from 1990 to JSON
-* `stationary.py` format JSON to nice PDF files
+* `stationery.py` format JSON to nice PDF files
* `printing.py` printing with CUPS via `lp`. Each document sent is recorded (job, key, printer, CUPS request id or the error) in `~/printerface/printer.pickle`, newest first and trimmed to `[Printing] result_count` (the sent emails and uploads have their own `result_count` under `[Gmail]` and `[Web]`), and listed on the job page. The file is written from the main loop only when something changed
* `derived.py` a cache, `~/printerface/derived.pickle`, of what is slow to work out from a stored job: its parsed pages and the names of its PDFs. At startup a job whose file is unchanged and whose parser is unchanged takes these from the cache (a thousand jobs in under a second, against about eight), and a job that has left the loaded history drops out of the file the next time it is written (at most every three minutes, and at shutdown). The PDFs are not redrawn when the stationery changes: Settings > Stationery counts the documents drawn under older stationery and redraws them on request
* `printstatus.py` read-only CUPS status for the Printers page (one `lpstat -t` in the C locale, cached for 10s), and the check of whether auto-printing can work. lpstat can show a stuck or stopped queue but not that a page was printed
@@ -54,6 +54,18 @@ Jobs, rendered PDFs, the email address book and `email.cfg` overrides live in `~
`PRINTERFACE_HOME` environment variable to use a different directory, for example to run a second instance
against a copy of the data on other ports (`lpd_port` and `http_port` in `defaults.cfg`/`email.cfg`).
+### Configuration
+
+`defaults.cfg` lists every setting; `~/printerface/email.cfg` overrides what you need to, under the same section names:
+
+* `[Stationery]` how documents are drawn: the company details, terms and logos on the PDFs. Settings > Stationery lists the values in use
+* `[Printing]` what is done with documents once drawn: `auto_types` and `auto_printer` for printing on arrival, and `result_count` for the printed history
+* `[Web]` the website documents are uploaded to (`base_url`, `api_key`), `auto_types` for uploading on arrival, and `result_count` for the upload history
+* `[Gmail]` the mail account and `result_count` for the sent history; `[Main]` ports, time zone and the like; `[History]` how many jobs to load and show
+
+These were `[Printing]` (the company details) and `[Robot]` (auto-printing) before. A file written for those is still read, with a
+notice in the log, and `tools/migrate_config.py` rewrites one in place (`--dry-run` shows the result first, and the original is kept).
+
### Email templates
The text offered when emailing a document comes from a template per document type: `invoice`, `purchase` and
diff --git a/defaults.cfg b/defaults.cfg
index 227ed7e..0217c60 100644
--- a/defaults.cfg
+++ b/defaults.cfg
@@ -2,7 +2,8 @@
from=printerface@localhost
to=chris@shucksmith.co.uk
-[Printing]
+# How documents are drawn: the company details and logos on the stationery
+[Stationery]
email=sales@yourdomain.com
website=www.yourdomain.com
vatreg=VAT Reg. GB-123 456 789
@@ -17,8 +18,6 @@ purch_instruction_fr=Veuillez confirmer reception de cette commande et sa\ndate
purch_instruction_en=Please contact immediately if any problems or\nqueries.
logo=logo.jpg
logo2=
-# How many printed documents to remember (newest first) on the Printed Documents page
-result_count=200
[Main]
summary_trim=AAAA,BBBBBB
@@ -37,9 +36,12 @@ auto_types=
# How many uploads to remember (newest first) on the Uploads page
result_count=120
-[Robot]
+# What is done with documents once drawn: the kinds printed as soon as they arrive, on which CUPS queue, and how
+# many printed documents to remember (newest first) on the Printed Documents page
+[Printing]
auto_types=Delvnote,Pick lst
auto_printer=HP_TONY
+result_count=200
[History]
loadqty=800
diff --git a/derived.py b/derived.py
index 9f11847..82f06ee 100644
--- a/derived.py
+++ b/derived.py
@@ -11,7 +11,7 @@
An entry is only trusted if
* the job file is the one it was made from (size and modification time),
* it was parsed by the same parser (`parse_stamp`: docparser.py and textutil.py),
-and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationary.py, the [Printing]
+and the PDFs it names are still on disk. How the PDFs were drawn (`render_stamp`: stationery.py, the [Stationery]
company details and the logos) is recorded with it, but a change does not redraw them by itself: the Stationery
settings page counts the jobs drawn under older stationery and has the button that redraws them.
"""
@@ -51,9 +51,9 @@ def parse_stamp():
def render_stamp():
- parts = [FORMAT, _source('stationary.py'), sorted(config.items('Printing'))]
+ parts = [FORMAT, _source('stationery.py'), sorted(config.items('Stationery'))]
for key in ('logo', 'logo2'):
- path = os.path.expanduser(config.get('Printing', key, fallback=''))
+ path = os.path.expanduser(config.get('Stationery', key, fallback=''))
try:
st = os.stat(path) if path else None
except OSError:
diff --git a/emailtemplates.py b/emailtemplates.py
index a6c09d9..c823cfd 100644
--- a/emailtemplates.py
+++ b/emailtemplates.py
@@ -144,7 +144,7 @@ def build_context(job, key, names=(), addresses=(), company=None):
all facts about all of them together, see summarise(): all.numbers, all.total, all.many, all.s
email the recipients: email.name ('Ann and Bob', or 'Sir or Madam' with none), email.address
job job.name, job.doctype, job.host
- company company.name, company.email, company.website, from the [Printing] settings
+ company company.name, company.email, company.website, from the [Stationery] settings
The default template has email, job and company but no doc or docs: for the other document types there
are no fields we know of."""
addresses = [a for a in addresses if a]
diff --git a/main.py b/main.py
index c0a43a1..2049566 100755
--- a/main.py
+++ b/main.py
@@ -11,7 +11,7 @@
import mailer
from mailer import JobMailer
from docparser import DocParser
-from stationary import DocFormatter
+from stationery import DocFormatter
from printing import getPrinters, printFile
import printing
import printstatus
@@ -28,6 +28,7 @@
import json
import time
import pytz
+import settings
from settings import config, HOME
import emailtemplates
from textutil import split_lines, load_job_pickle, load_user_pickles, PICKLE_PROTOCOL
@@ -276,8 +277,8 @@ def cleanJob(j, entry=None):
# all done
j['autoprint'] = None
- if j['doctype'] in config.get('Robot', 'auto_types').split(','):
- j['autoprint'] = config.get('Robot', 'auto_printer')
+ if j['doctype'] in config.get('Printing', 'auto_types').split(','):
+ j['autoprint'] = config.get('Printing', 'auto_printer')
return outcome
def register_accounts(j):
@@ -372,15 +373,15 @@ def job(query_string=dict(), resp=None):
'templ': job.get('templ'),
'doctype': job.get('doctype'),
'autofmt': job.get('autofmt'),
- 'stationary':
+ 'stationery':
dict([ (' '.join(k), '{base}/pdf/{pdf}'.format(base=base_uri, pdf=v)) for k,v in job.get('groupfiles', {}).items() ])
}
return json.dumps(output, indent=3), 'text/json'
def printers(query_string='', resp=None):
"""What CUPS says about the printers and the auto-print setup. Read-only: lpstat is the only thing run."""
- auto_types = [t for t in config.get('Robot', 'auto_types').split(',') if t]
- auto_printer = config.get('Robot', 'auto_printer')
+ auto_types = [t for t in config.get('Printing', 'auto_types').split(',') if t]
+ auto_printer = config.get('Printing', 'auto_printer')
try:
st = printstatus.status()
error = None
@@ -427,9 +428,25 @@ def regenerate_stationery():
derivedcache.dirty = True
return len(stale)
+STATIONERY_LOGOS = ('logo', 'logo2')
+
+def stationery_details():
+ """The [Stationery] settings the documents are drawn with, as the Stationery page lists them: each key with its
+ value (split on the \\n that stands for a line break), whether email.cfg sets it or it is the default, and for a
+ logo whether the file is there."""
+ rows = []
+ for key in config.options('Stationery'):
+ value = config.get('Stationery', key)
+ row = dict(key=key, lines=value.split('\\n') if value else [], set=('Stationery', key) in settings.overridden, logo=None)
+ if key in STATIONERY_LOGOS and value:
+ path = os.path.expanduser(value)
+ row['logo'] = (path, os.path.isfile(path))
+ rows.append(row)
+ return rows
+
def settings_stationery(query_string='', postreq=None, resp=None):
- """How many loaded jobs have PDFs drawn under older stationery (a change to stationary.py, or to the company
- details or logos under [Printing]), with the button that draws them again. It blocks the server while it works,
+ """How many loaded jobs have PDFs drawn under older stationery (a change to stationery.py, or to the company
+ details or logos under [Stationery]), with the button that draws them again. It blocks the server while it works,
about a second for every few hundred jobs, so it is an admin action rather than something done on its own."""
if postreq is not None:
n = regenerate_stationery() if 'regenerate' in postreq else 0
@@ -438,7 +455,8 @@ def settings_stationery(query_string='', postreq=None, resp=None):
redrawn = int(query_string.get('redrawn', [''])[0])
except ValueError:
redrawn = None
- return ( template_lookup.get_template("/settings_stationery.html").render(stale=len(derivedcache.stale(jobs)), total=len(jobs), redrawn=redrawn), 'text/html')
+ return ( template_lookup.get_template("/settings_stationery.html").render(stale=len(derivedcache.stale(jobs)), total=len(jobs), redrawn=redrawn,
+ details=stationery_details(), config_path=os.path.join(HOME, 'email.cfg')), 'text/html')
def settings_web(query_string='', resp=None):
"""Where documents are uploaded to. Read only: it is set under [Web] in email.cfg. The API key is never shown, only
@@ -491,7 +509,7 @@ def printfn(query_string='', postreq=None, resp=None):
return doMessage(title='Printing', message='Could not find the document, or a problem printing it! Source: %s sent to printer %s
' % (html.escape(str(docf)), html.escape(printer)))
def company_info():
- printing = lambda k: config.get('Printing', k, fallback='')
+ printing = lambda k: config.get('Stationery', k, fallback='')
return {'name': printing('address').split('\\n')[0].strip(), 'email': printing('email'), 'website': printing('website')}
def settings_templates(query_string='', postreq=None, resp=None):
diff --git a/settings.py b/settings.py
index 8ec57f6..c245c6b 100644
--- a/settings.py
+++ b/settings.py
@@ -1,19 +1,54 @@
-# Locations and configuration shared by main, mailer and stationary.
+# Locations and configuration shared by main, mailer and stationery.
#
# PRINTERFACE_HOME holds the stored jobs, rendered PDFs, email address book and email.cfg overrides.
# It defaults to ~/printerface; set the environment variable to run a second instance (for example a
# shadow instance on a copy of the data) without touching the live one.
import configparser
+import io
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
HOME = os.path.expanduser(os.environ.get('PRINTERFACE_HOME', '~/printerface'))
+# [Stationery] is how documents are drawn (company details, logos), [Printing] is what is done with them once drawn
+# (auto-print, the printed history). They used to be [Printing] and [Robot]; a file written for that is still read,
+# the keys that were in [Printing] going to [Stationery] and those in [Robot] to [Printing]. tools/migrate_config.py
+# rewrites a file to the new layout.
+
+# the (section, key) pairs that email.cfg sets, for the settings pages to mark as changed from the defaults
+overridden = set()
+
+def translate(user, company_keys):
+ """(RawConfigParser in the current layout, whether it was in the old one) for a RawConfigParser read from email.cfg."""
+ out = configparser.RawConfigParser()
+ legacy = False
+ for section in user.sections():
+ for key, value in user.items(section):
+ target = section
+ if section == 'Robot':
+ target, legacy = 'Printing', True
+ elif section == 'Printing' and key in company_keys:
+ target, legacy = 'Stationery', True
+ if not out.has_section(target):
+ out.add_section(target)
+ out.set(target, key, value)
+ return out, legacy
+
def load_config():
config = configparser.ConfigParser()
with open(os.path.join(BASE_DIR, 'defaults.cfg')) as f:
config.read_file(f)
- config.read(os.path.join(HOME, 'email.cfg'))
+ user = configparser.RawConfigParser()
+ user.read(os.path.join(HOME, 'email.cfg'))
+ user, legacy = translate(user, set(config.options('Stationery')))
+ if legacy:
+ print('[config] %s/email.cfg uses the old [Printing] and [Robot] sections; read as [Stationery] and [Printing]. '
+ 'Run tools/migrate_config.py to update it' % HOME)
+ buf = io.StringIO()
+ user.write(buf)
+ config.read_string(buf.getvalue())
+ overridden.clear()
+ overridden.update((section, key) for section in user.sections() for key in user.options(section))
return config
config = load_config()
diff --git a/stationary.py b/stationery.py
similarity index 95%
rename from stationary.py
rename to stationery.py
index 6023ec6..60fa6a7 100644
--- a/stationary.py
+++ b/stationery.py
@@ -21,27 +21,27 @@ def headerDetails(c, ctx, doctype="DELIVERY NOTE", terms_key='terms'):
textobject = c.beginText(0*cm, top-1.5*cm)
textobject.setFont("Helvetica", 8)
- textobject.textLines(config.get('Printing', 'address').split("\\n"))
+ textobject.textLines(config.get('Stationery', 'address').split("\\n"))
c.drawText(textobject)
textobject = c.beginText(5.5*cm, top-1.5*cm)
textobject.setFont("Helvetica", 8)
- textobject.textLine(config.get('Printing', 'vatreg'))
- textobject.textLine(config.get('Printing', 'fax1'))
- textobject.textLine(config.get('Printing', 'fax2'))
- textobject.textLine(config.get('Printing', 'email'))
- textobject.textLine(config.get('Printing', 'website'))
+ textobject.textLine(config.get('Stationery', 'vatreg'))
+ textobject.textLine(config.get('Stationery', 'fax1'))
+ textobject.textLine(config.get('Stationery', 'fax2'))
+ textobject.textLine(config.get('Stationery', 'email'))
+ textobject.textLine(config.get('Stationery', 'website'))
c.drawText(textobject)
c.setFont("Helvetica", 18)
c.drawRightString(pagewidth, top, doctype)
c.restoreState()
- c.drawImage(os.path.expanduser(config.get('Printing', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
- if config.get('Printing', 'logo2'):
- c.drawImage(os.path.expanduser(config.get('Printing', 'logo2')), 5.0*cm, top-0.9*cm, width=5.0*cm,height=1.4*cm, preserveAspectRatio=True, anchor='sw')
+ c.drawImage(os.path.expanduser(config.get('Stationery', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
+ if config.get('Stationery', 'logo2'):
+ c.drawImage(os.path.expanduser(config.get('Stationery', 'logo2')), 5.0*cm, top-0.9*cm, width=5.0*cm,height=1.4*cm, preserveAspectRatio=True, anchor='sw')
c.setFont("Helvetica", 10)
- c.drawString(0, 0.40*cm, config.get('Printing', terms_key))
+ c.drawString(0, 0.40*cm, config.get('Stationery', terms_key))
# marker of progress on CLI
sys.stdout.write('.')
@@ -176,7 +176,7 @@ def deliveryNotePage(c, ctx, mark):
w = pagewidth / 2.0
h = 0.45*cm
topBox(c, 0, y, w=w, h=h, title='SECTION TO BE COMPLETED BY CUSTOMER', content='', align='c')
- topBox(c, w, y, w=w, h=h, title=config.get('Printing', 'inv_rhs'), content='', align='c')
+ topBox(c, w, y, w=w, h=h, title=config.get('Stationery', 'inv_rhs'), content='', align='c')
y = y-h
h = 0.85*cm
leftBox(c, 0, y, w=w, h=h, title='SIGNED', content='')
@@ -319,7 +319,7 @@ def purchasePage(c, ctx, mark):
(x, y1) = leftBox(c, x, y0-vpad, w=pagewidth-x, title='TOTAL NET', content=price_tot, colfmt='dr')
w = 10.4*cm
- (x, y) = topBox(c, 0, y0-vpad, w=w, h=3.7*cm, pad=0.2*cm, title=config.get('Printing', 'purch_instruction_header'), align='c', content=config.get('Printing', 'purch_instruction_en').replace("\\n", '\n'))
+ (x, y) = topBox(c, 0, y0-vpad, w=w, h=3.7*cm, pad=0.2*cm, title=config.get('Stationery', 'purch_instruction_header'), align='c', content=config.get('Stationery', 'purch_instruction_en').replace("\\n", '\n'))
c.showPage()
@@ -341,8 +341,8 @@ def statementPage(c, ctx, mark):
textobject.setTextOrigin(divide+vpad, top-vpad)
textobject.setFont("Helvetica", 8)
textobject.textLines('PLEASE DETACH AND RETURN\nWITH YOUR REMITTANCE TO:')
- textobject.textLines(config.get('Printing', 'address').replace("\\n", '\n'))
- textobject.textLines(config.get('Printing', 'fax1'))
+ textobject.textLines(config.get('Stationery', 'address').replace("\\n", '\n'))
+ textobject.textLines(config.get('Stationery', 'fax1'))
c.drawText(textobject)
h = 0.85*cm
@@ -417,7 +417,7 @@ def genericPage(c, data, title=None, fontsz=7, landsc=False, overlay=None, decor
if title:
c.setFont("Helvetica", 18)
c.drawRightString(pagewidth, top, title)
- c.drawImage(os.path.expanduser(config.get('Printing', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
+ c.drawImage(os.path.expanduser(config.get('Stationery', 'logo')) , 0.0*cm, top-1.1*cm, width=7.0*cm,height=1.8*cm, preserveAspectRatio=True, anchor='sw')
y = y - 2.0*cm
textobject = c.beginText()
@@ -700,7 +700,7 @@ def getBestPageFormat(self, plaintext):
import unittest
from datetime import datetime
-class TestStationary(unittest.TestCase):
+class TestStationery(unittest.TestCase):
def setUp(self):
import tempfile
diff --git a/test_config.py b/test_config.py
new file mode 100644
index 0000000..7603e64
--- /dev/null
+++ b/test_config.py
@@ -0,0 +1,112 @@
+# The [Stationery] / [Printing] layout of email.cfg, and reading and rewriting the old [Printing] / [Robot] one.
+import configparser
+import importlib.util
+import io
+import os
+import unittest
+
+import settings
+
+spec = importlib.util.spec_from_file_location('migrate_config', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tools', 'migrate_config.py'))
+migrate_config = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(migrate_config)
+
+OLD = """[Email]
+to=me@example.com
+
+# the company, as it appears on the paper
+[Printing]
+email=sales@example.com
+address=A COMPANY\\nA STREET
+; the terms, over two lines
+terms=All goods sold in accordance
+ with our Terms
+logo=~/logo.jpg
+result_count=50
+
+[Robot]
+# what is printed on arrival
+auto_types=Delvnote,Invoice
+auto_printer=DESK_LASER
+
+[Gmail]
+login_password=pass%%word
+"""
+
+
+def parse(text):
+ c = configparser.RawConfigParser()
+ c.read_string(text)
+ return c
+
+
+class TestMigrate(unittest.TestCase):
+ def test_keys_move_to_the_sections_they_belong_in(self):
+ new = parse(migrate_config.migrate(OLD))
+ self.assertEqual(['Email', 'Stationery', 'Printing', 'Gmail'], new.sections())
+ self.assertEqual(['email', 'address', 'terms', 'logo'], new.options('Stationery'))
+ self.assertEqual(['auto_types', 'auto_printer', 'result_count'], new.options('Printing'))
+ old = parse(OLD)
+ self.assertEqual(old.get('Printing', 'terms'), new.get('Stationery', 'terms')) # the continuation line came too
+ self.assertEqual('DESK_LASER', new.get('Printing', 'auto_printer'))
+ self.assertEqual('50', new.get('Printing', 'result_count'))
+ self.assertEqual('pass%%word', new.get('Gmail', 'login_password'))
+
+ def test_comments_travel_with_their_keys(self):
+ text = migrate_config.migrate(OLD)
+ self.assertIn('; the terms, over two lines\nterms=', text)
+ self.assertIn('# what is printed on arrival\nauto_types=', text)
+
+ def test_a_file_in_the_new_layout_is_left_alone(self):
+ new = migrate_config.migrate(OLD)
+ self.assertEqual(new, migrate_config.migrate(new))
+ self.assertEqual('[Email]\nto=x\n', migrate_config.migrate('[Email]\nto=x\n'))
+
+ def test_only_robot_or_only_printing(self):
+ only_robot = parse(migrate_config.migrate('[Robot]\nauto_printer=X\n[Main]\ntz=UTC\n'))
+ self.assertEqual({'auto_printer': 'X'}, dict(only_robot.items('Printing')))
+ only_company = parse(migrate_config.migrate('[Printing]\nvatreg=GB1\n[Main]\ntz=UTC\n'))
+ self.assertEqual({'vatreg': 'GB1'}, dict(only_company.items('Stationery')))
+ self.assertFalse(only_company.has_section('Printing'))
+
+
+class TestReadingTheOldLayout(unittest.TestCase):
+ keys = {'email', 'address', 'terms', 'logo'}
+
+ def test_translate(self):
+ out, legacy = settings.translate(parse(OLD), self.keys)
+ self.assertTrue(legacy)
+ self.assertEqual('A COMPANY\\nA STREET', out.get('Stationery', 'address'))
+ self.assertEqual({'auto_types': 'Delvnote,Invoice', 'auto_printer': 'DESK_LASER', 'result_count': '50'}, dict(out.items('Printing')))
+
+ def test_the_new_layout_is_not_legacy(self):
+ out, legacy = settings.translate(parse(migrate_config.migrate(OLD)), self.keys)
+ self.assertFalse(legacy)
+
+ def test_defaults_are_in_the_new_layout(self):
+ defaults = settings.configparser.ConfigParser()
+ with open(os.path.join(settings.BASE_DIR, 'defaults.cfg')) as f:
+ defaults.read_file(f)
+ self.assertIn('address', defaults.options('Stationery'))
+ self.assertEqual({'auto_types', 'auto_printer', 'result_count'}, set(defaults.options('Printing')))
+ self.assertFalse(defaults.has_section('Robot'))
+
+ def test_loading_an_old_file_gives_the_new_sections_and_notes_what_was_set(self):
+ import tempfile
+ with tempfile.TemporaryDirectory() as home:
+ with open(os.path.join(home, 'email.cfg'), 'w') as f:
+ f.write(OLD.replace('pass%%word', 'password'))
+ old_home, settings.HOME = settings.HOME, home
+ self.addCleanup(setattr, settings, 'HOME', old_home)
+ self.addCleanup(lambda: (settings.load_config(),))
+ config = settings.load_config()
+ self.assertEqual('DESK_LASER', config.get('Printing', 'auto_printer'))
+ self.assertEqual('A COMPANY\\nA STREET', config.get('Stationery', 'address'))
+ self.assertEqual('50', config.get('Printing', 'result_count'))
+ self.assertIn(('Stationery', 'terms'), settings.overridden)
+ self.assertIn(('Printing', 'auto_printer'), settings.overridden)
+ self.assertNotIn(('Stationery', 'vatreg'), settings.overridden)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/test_derived.py b/test_derived.py
index 1491c99..c744181 100644
--- a/test_derived.py
+++ b/test_derived.py
@@ -79,14 +79,14 @@ class TestStamps(unittest.TestCase):
def test_render_stamp_follows_the_company_details_and_logos(self):
before = derived.render_stamp()
self.assertEqual(before, derived.render_stamp())
- old = config.get('Printing', 'terms')
- config.set('Printing', 'terms', old + ' and more')
- self.addCleanup(config.set, 'Printing', 'terms', old)
+ old = config.get('Stationery', 'terms')
+ config.set('Stationery', 'terms', old + ' and more')
+ self.addCleanup(config.set, 'Stationery', 'terms', old)
self.assertNotEqual(before, derived.render_stamp())
- config.set('Printing', 'terms', old)
+ config.set('Stationery', 'terms', old)
with tempfile.NamedTemporaryFile(suffix='.jpg') as logo:
- config.set('Printing', 'logo2', logo.name)
- self.addCleanup(config.set, 'Printing', 'logo2', '')
+ config.set('Stationery', 'logo2', logo.name)
+ self.addCleanup(config.set, 'Stationery', 'logo2', '')
with_logo = derived.render_stamp()
self.assertNotEqual(before, with_logo)
logo.write(b'changed')
diff --git a/test_integration.py b/test_integration.py
index 909cbae..7352c8e 100644
--- a/test_integration.py
+++ b/test_integration.py
@@ -24,7 +24,7 @@
import derived
import uploader
import emailtemplates
-from stationary import DocFormatter
+from stationery import DocFormatter
from lpdserver import LpdServer
from httpserver import HttpServer
from textutil import split_lines
@@ -143,9 +143,9 @@ def tearDownClass(cls):
def test_printers_page(self):
printstatus.reset_cache()
- old = main.config.get('Robot', 'auto_printer')
+ old = main.config.get('Printing', 'auto_printer')
try:
- main.config.set('Robot', 'auto_printer', 'DESK_LASER')
+ main.config.set('Printing', 'auto_printer', 'DESK_LASER')
r, body = self.get('/printers')
self.assertEqual(r.status, 200)
text = body.decode()
@@ -153,11 +153,11 @@ def test_printers_page(self):
self.assertIn(expected, text)
# DESK_LASER has a 2017 job waiting
self.assertIn('may not be working', text)
- main.config.set('Robot', 'auto_printer', 'NOPE')
+ main.config.set('Printing', 'auto_printer', 'NOPE')
printstatus.reset_cache()
self.assertIn('no printer called NOPE', self.get('/printers')[1].decode())
finally:
- main.config.set('Robot', 'auto_printer', old)
+ main.config.set('Printing', 'auto_printer', old)
printstatus.reset_cache()
def test_printers_page_without_cups(self):
@@ -265,7 +265,8 @@ def test_http_endpoints(self):
r, body = self.get('/job?name=' + name)
parsed = json.loads(body.decode('utf-8'))
self.assertEqual('12345', parsed['parsed']['ACC001'][0]['doc_num'])
- pdf_uri = parsed['stationary']['ACC001']
+ pdf_uri = parsed['stationery']['ACC001']
+ self.assertNotIn('stationary', parsed) # the key's old spelling
self.assertTrue(pdf_uri.endswith('.pdf'))
r, body = self.get('/raw?name=' + name)
@@ -885,9 +886,20 @@ def test_stationery_page_redraws_jobs_drawn_under_older_stationery(self):
j = self.send_invoice(pages=1, totals=['144.00'], net='120.00', vat='24.00')
self.assertEqual(main.derivedcache.render_stamp, j['render_stamp'])
self.assertIn(b'were drawn under today', self.get('/settings/stationery')[1])
- old = config_terms = main.config.get('Printing', 'terms')
- main.config.set('Printing', 'terms', old + ' (changed)')
- self.addCleanup(main.config.set, 'Printing', 'terms', old)
+ body = self.get('/settings/stationery')[1]
+ self.assertIn(b'address', body) # the [Stationery] settings the documents are drawn with
+ self.assertIn(b'terms_purch', body)
+ self.assertIn(b'YOUR DOMAIN LTD.', body) # the address, one line per \\n
+ self.assertIn(b'SOME BUSINESS PARK', body)
+ self.assertNotIn(b'\\nSOME', body)
+ self.assertNotIn(b'label-important">missing', body) # logo.jpg is found, logo2 is blank
+ main.config.set('Stationery', 'logo2', '/no/such/logo.jpg')
+ self.addCleanup(main.config.set, 'Stationery', 'logo2', '')
+ self.assertIn(b'label-important">missing', self.get('/settings/stationery')[1])
+ main.config.set('Stationery', 'logo2', '')
+ old = config_terms = main.config.get('Stationery', 'terms')
+ main.config.set('Stationery', 'terms', old + ' (changed)')
+ self.addCleanup(main.config.set, 'Stationery', 'terms', old)
main.derivedcache.render_stamp = derived.render_stamp() # what the next start would see
self.addCleanup(setattr, main.derivedcache, 'render_stamp', derived.render_stamp())
body = self.get('/settings/stationery')[1]
@@ -1080,10 +1092,10 @@ def test_the_template_editor_ignores_actions_that_arrive_by_get(self):
def test_delivery_notes_are_auto_printed(self):
j = self.send_invoice('Delvnote')
- self.assertEqual(main.config.get('Robot', 'auto_printer'), j['autoprint'])
+ self.assertEqual(main.config.get('Printing', 'auto_printer'), j['autoprint'])
self.printed.assert_called_once()
path, printer = self.printed.call_args[0]
- self.assertEqual(main.config.get('Robot', 'auto_printer'), printer)
+ self.assertEqual(main.config.get('Printing', 'auto_printer'), printer)
self.assertTrue(path.startswith(main.pdfdir) and path.endswith('.pdf'), path)
# an invoice is not an auto-print type
self.printed.reset_mock()
diff --git a/tools/migrate_config.py b/tools/migrate_config.py
new file mode 100755
index 0000000..d8e1579
--- /dev/null
+++ b/tools/migrate_config.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env python3.11
+"""Rewrite an email.cfg written for the old sections to the current ones, keeping its comments and order:
+
+ [Printing] company details and logos -> [Stationery]
+ [Robot] auto_types, auto_printer -> [Printing] (with the printed history's result_count)
+
+ tools/migrate_config.py [PATH] [--dry-run]
+
+PATH defaults to ~/printerface/email.cfg (or $PRINTERFACE_HOME/email.cfg). The original is kept beside it as
+email.cfg.before-sections, unless that exists already. A file already in the new layout is left alone. Printerface
+reads the old layout too, with a notice in its log, so this is tidying, not a requirement.
+"""
+import argparse
+import configparser
+import os
+import re
+import shutil
+import sys
+
+HEADER = re.compile(r'^\[([^\]]+)\]\s*$')
+KEY = re.compile(r'^([^\s#;=:\[][^=:]*?)\s*[=:]')
+
+
+def company_keys():
+ base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ c = configparser.RawConfigParser()
+ c.read(os.path.join(base, 'defaults.cfg'))
+ return set(c.options('Stationery'))
+
+
+def blocks(text):
+ """[(section or None, [entry, ...])]. An entry is the comment and blank lines before a key, the key's line and its
+ continuation lines, as one list of lines; lines after the last key of a section are an entry with no key."""
+ out = [(None, [[]])]
+ for line in text.splitlines():
+ m = HEADER.match(line)
+ if m:
+ out.append((m.group(1), [[]]))
+ continue
+ entries = out[-1][1]
+ if KEY.match(line):
+ entries[-1].append(line)
+ entries.append([])
+ elif line[:1] in (' ', '\t') and line.strip() and len(entries) > 1 and entries[-1] == []:
+ entries[-2].append(line) # a continuation of the previous value
+ else:
+ entries[-1].append(line)
+ return out
+
+
+def key_of(entry):
+ for line in entry:
+ m = KEY.match(line)
+ if m:
+ return m.group(1).strip()
+ return None
+
+
+def migrate(text, keys=None):
+ keys = company_keys() if keys is None else keys
+ parts = blocks(text)
+ names = [name for name, _ in parts]
+ old_printing = [e for name, es in parts if name == 'Printing' for e in es]
+ if 'Robot' not in names and not any(key_of(e) in keys for e in old_printing):
+ return text
+ stationery = [e for e in old_printing if key_of(e) in keys]
+ printing = [e for name, es in parts if name == 'Robot' for e in es if key_of(e) is not None]
+ printing += [e for e in old_printing if key_of(e) not in keys and key_of(e) is not None]
+ trailer = {}
+ out = []
+ placed_printing = False
+
+ def section(name, entries):
+ lines = ['[%s]' % name]
+ for e in entries:
+ if key_of(e) is not None:
+ lines.extend(e)
+ return lines
+
+ for name, entries in parts:
+ if name is None:
+ preamble = [l for e in entries for l in e]
+ out.extend(preamble)
+ continue
+ if out and out[-1].strip():
+ out.append('')
+ if name == 'Printing':
+ if stationery:
+ out.extend(section('Stationery', stationery))
+ if 'Robot' not in names and printing:
+ out.append('')
+ out.extend(section('Printing', printing))
+ placed_printing = True
+ elif name == 'Robot':
+ out.extend(section('Printing', printing))
+ placed_printing = True
+ else:
+ out.append('[%s]' % name)
+ for e in entries:
+ out.extend(e)
+ if printing and not placed_printing:
+ out.append('')
+ out.extend(section('Printing', printing))
+ while out and not out[-1].strip():
+ out.pop()
+ return '\n'.join(out) + '\n'
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('path', nargs='?', default=os.path.join(os.path.expanduser(os.environ.get('PRINTERFACE_HOME', '~/printerface')), 'email.cfg'))
+ ap.add_argument('--dry-run', action='store_true', help='show the sections it would write, change nothing')
+ args = ap.parse_args()
+ with open(args.path) as f:
+ old = f.read()
+ new = migrate(old)
+ if new == old:
+ print('%s is already in the current layout' % args.path)
+ return
+ check = configparser.RawConfigParser()
+ check.read_string(new)
+ print('%s: sections now %s' % (args.path, check.sections()))
+ if args.dry_run:
+ return
+ backup = args.path + '.before-sections'
+ if not os.path.exists(backup):
+ shutil.copy2(args.path, backup)
+ mode = os.stat(args.path).st_mode & 0o777
+ tmp = args.path + '.tmp'
+ with open(tmp, 'w') as f:
+ f.write(new)
+ os.chmod(tmp, mode)
+ os.replace(tmp, args.path)
+ print('rewritten; the original is %s' % backup)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/web/debug.html b/web/debug.html
index b42bdcf..89bcf04 100644
--- a/web/debug.html
+++ b/web/debug.html
@@ -19,7 +19,7 @@
${pformatted}
- keys: ${job['groupkey']}
| Setting | Value | |
|---|---|---|
${d['key'] | h} |
+
+ % if d['lines']:
+ % for line in d['lines']:
+ ${line | h}${'' if loop.last else ' '} + % endfor + % else: + blank + % endif + % if d['logo']: + + % if d['logo'][1]: + ${d['logo'][0] | h} + % else: + missing ${d['logo'][0] | h} + % endif + % endif + |
+ ${'set' if d['set'] else ''} | +