From ef6d9c17d27be711f543e59a9b59523838330250 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Wed, 18 Nov 2026 16:16:19 +0000 Subject: [PATCH 01/31] Normalise mixed tab/space indentation (py2 tab=8 semantics preserved) Co-Authored-By: Claude Sonnet 5.5 --- main.py | 4 ++-- stationary.py | 32 ++++++++++++++++---------------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/main.py b/main.py index e13561b..3b24d5c 100755 --- a/main.py +++ b/main.py @@ -218,8 +218,8 @@ def home(query_string='', resp=None): return template_lookup.get_template("/home.html").render(email_fails=email_fails, account=account), 'text/html' def getrows_byslice(seq, rowlen): - for start in xrange(0, len(seq), rowlen): - yield seq[start:start+rowlen] + for start in xrange(0, len(seq), rowlen): + yield seq[start:start+rowlen] def recent(query_string=dict(), resp=None): query = query_string.get('query', [''])[0] diff --git a/stationary.py b/stationary.py index ba74a85..0f6f1f8 100644 --- a/stationary.py +++ b/stationary.py @@ -331,8 +331,8 @@ def statementPage(c, ctx, mark): c.translate(0.8*cm,0.8*cm) # entire page breaks at 12cm, LHS is tear off (originally perferated) - watermark(c, mark=mark, x=6*cm, fontsz=36) - watermark(c, mark=mark, x=16*cm, fontsz=20) + watermark(c, mark=mark, x=6*cm, fontsz=36) + watermark(c, mark=mark, x=16*cm, fontsz=20) headerDetails(c, ctx, 'Statement') @@ -348,7 +348,7 @@ def statementPage(c, ctx, mark): h = 0.85*cm y = 24.6*cm - (x,y0) = topBox(c, 0*cm, y, h=3.8*cm, w=8.2*cm, title='TO', content=ctx['addr_invoice']) + (x,y0) = topBox(c, 0*cm, y, h=3.8*cm, w=8.2*cm, title='TO', content=ctx['addr_invoice']) w = divide - vpad - (x + vpad) (x0,y) = topBox(c, x+vpad, y, h=1.25*cm, w=w, title='ACCOUNT NO.', content=ctx['accno']) (x0,y) = topBox(c, x+vpad, y, h=1.25*cm, w=w, title='DATE', content=ctx['date']) @@ -481,7 +481,7 @@ def writeInvoice(self, ctx ): for page in pages_by_docnum[k]: accountNotePage(c, page, 'ACCOUNTS COPY') - c.save() + c.save() rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir) return rendered_pdfs, ('Group',) @@ -559,10 +559,10 @@ def writeStatement(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for page in v: + for page in v: statementPage(c, page, 'CUSTOMER COPY') - c.save() + c.save() rendered_pdfs[ (acc,) ] = os.path.relpath(p, self.jobdir) p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), 'accounts', "%s-%s.pdf" % (ctx['name'], 'accounts')) @@ -570,10 +570,10 @@ def writeStatement(self, ctx): c = canvas.Canvas(p, pagesize=A4) for (acc,v) in ctx['parsed'].iteritems(): - for page in v: + for page in v: statementPage(c, page, 'ACCOUNTS COPY') - c.save() + c.save() rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir) # protocol: key tuples must all be same length, second tuple is key descriptions @@ -590,7 +590,7 @@ def writeDelnote(self, ctx): for page in v: deliveryNotePage(c, page, mark) - c.save() + c.save() rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir) return rendered_pdfs, ('type',) @@ -604,10 +604,10 @@ def writeRemittance(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for page in v: + for page in v: remittancePage(c, page, 'CUSTOMER COPY') - c.save() + c.save() rendered_pdfs[ (acc,) ] = os.path.relpath(p, self.jobdir) p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), 'accounts', "%s-%s.pdf" % (ctx['name'], 'accounts')) @@ -616,10 +616,10 @@ def writeRemittance(self, ctx): for (acc,v) in ctx['parsed'].iteritems(): - for page in v: + for page in v: remittancePage(c, page, 'ACCOUNTS COPY') - c.save() + c.save() rendered_pdfs[ ('accounts',) ] = os.path.relpath(p, self.jobdir) # protocol: key tuples must all be same length, second tuple is key descriptions @@ -637,10 +637,10 @@ def writePurchase(self, ctx): c = canvas.Canvas(p, pagesize=A4) for mark in marks: - for page in v: + for page in v: purchasePage(c, page, mark) - c.save() + c.save() rendered_pdfs[ ("%s%s" % (acc, bundle),) ] = os.path.relpath(p, self.jobdir) return rendered_pdfs, ('type', ) @@ -820,7 +820,7 @@ def test_statement(self): self.assertEquals( ({('SMP109',): '2014/SMP109/blahstate-SMP109.pdf', ('accounts',): '2014/accounts/blahstate-accounts.pdf'}, ('Group',) ), p) def test_cnote(self): - # CREDIT NOTE / INVOICE paperwork + # CREDIT NOTE / INVOICE paperwork extra = dict( doctype='CREDIT NOTE', summ_code='5\n'*4, summ_netamt='12345.67\n'*4, From 25cb4a770e0f837665eda0bbc3513d08690f2904 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Wed, 18 Nov 2026 16:22:18 +0000 Subject: [PATCH 02/31] Port to python 3.11 Mechanical py2 -> py3 changes plus the behaviour that 2to3 does not catch: * textutil.split_lines(): python 3 str.splitlines() also splits on \f, \v, \x1c-\x1e and \x85, which shifts every fixed row the parsers address. Keep the python 2 semantics (\n, \r, \r\n only). * Regexes over print data use re.ASCII so 8-bit characters are still blanked as they were for python 2 str, keeping /raw output pure ASCII. * lpdserver: bytes protocol, payload and control file decoded as latin-1 (one byte, one column). Gather terminator fragments instead of popping the first one. Fix the unknown-message-type log line. * httpserver: bytes through the request/response path; handler results may be str, bytes or a file. Drop cgi/mimetools. POST bodies parsed with parse_qs and the response is now actually sent. * Pickles: load python 2 job pickles as latin-1; user entered pickles (address book, mail results) are utf-8 and converted on load. Write protocol 2 so python 2.7 can still read them during cutover. * mailer: result_count is an int (comparing int > str crashed at startup). * printing: sys.platform is 'linux', not 'linux2'; decode lpstat output. * settings.py: PRINTERFACE_HOME overrides ~/printerface, shared config loading. * Templates: drop .decode('utf-8'), iteritems. Co-Authored-By: Claude Sonnet 5.5 --- .travis.yml | 7 --- datamine.py | 37 ++++++------- docparser.py | 38 +++++++------ httpserver.py | 118 ++++++++++++++++++++-------------------- lpdserver.py | 64 ++++++++++++---------- mailer.py | 48 ++++++++-------- main.py | 114 ++++++++++++++++++-------------------- printing.py | 8 +-- settings.py | 19 +++++++ stationary.py | 81 +++++++++++++-------------- textutil.py | 91 +++++++++++++++++++++++++++++++ web/debug.html | 2 +- web/pdf.html | 4 +- web/sent.html | 2 +- web/settings_email.html | 4 +- 15 files changed, 369 insertions(+), 268 deletions(-) delete mode 100644 .travis.yml create mode 100644 settings.py create mode 100644 textutil.py diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 1e7273c..0000000 --- a/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: python -python: - - "2.7" -install: "pip install -r requirements.txt" - -script: - - python -m unittest discover --pattern=*.py diff --git a/datamine.py b/datamine.py index 3a07bda..5585433 100644 --- a/datamine.py +++ b/datamine.py @@ -1,19 +1,18 @@ -#!/usr/bin/env python2.7 -from __future__ import with_statement - +#!/usr/bin/env python3.11 from datetime import datetime from docparser import DocParser from printing import getPrinters, printFile +from settings import HOME +from textutil import load_job_pickle, split_lines import sys import pickle import os import re -from StringIO import StringIO import collections import traceback -data_dir = os.path.expanduser("~/printerface/data/") +data_dir = os.path.join(HOME, "data") jobdir = os.path.join(data_dir, 'pickle') jobs = [] @@ -29,8 +28,8 @@ def recover(invf, invl): for x in reversed(sorted( os.listdir(os.path.join(jobdir, yyyymmdir)) )): p = os.path.join(jobdir, yyyymmdir, x) if not os.path.isfile(p): continue - with file(p, "rb") as f: - s = pickle.load(f) + with open(p, "rb") as f: + s = load_job_pickle(f) s['name'] = x; jobs.append(s) print(' recovering %s %s' % (p, s['name'])) @@ -38,7 +37,7 @@ def recover(invf, invl): if len(jobs) > loadQty: break if len(jobs) > loadQty: break -control_char_re = re.compile('[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"')) +control_char_re = re.compile(r'[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'), re.ASCII) def cleanJob(j, invf, invl): @@ -67,9 +66,9 @@ def handlePr1(j, dest=os.path.expanduser('/tmp/pr1')): suppliers = collections.defaultdict(int) szs = collections.defaultdict(int) with open(dest, 'w') as f: - for part in filter(None, j['plain'].split("\f")): + for part in [p for p in j['plain'].split("\f") if p]: if len(part.strip()) > 0: - for l in part.splitlines(): + for l in split_lines(part): if len(l.strip()) == 0: continue if 'STOCK MANAGEMENT' in l: continue if '=' * 46 in l: continue @@ -87,22 +86,22 @@ def handlePr1(j, dest=os.path.expanduser('/tmp/pr1')): suppliers[sup] += 1 sz = l[48:52] szs[sz] += 1 - print l + print(l) # l can spill over 130 characters if last column is negative (1) if len(l) > 129: l = l[0:129] f.write(l) f.write('\n') - print groups - print suppliers - print szs + print(groups) + print(suppliers) + print(szs) with open(os.path.expanduser('/tmp/groups'), 'w') as f: - for k,v in groups.iteritems(): + for k,v in groups.items(): f.write("%3d %-40s\n" % (k, v)) with open(os.path.expanduser('/tmp/sizes'), 'w') as f: - for k,v in szs.iteritems(): + for k,v in szs.items(): f.write("%s\n" % k) with open(os.path.expanduser('/tmp/suppliers'), 'w') as f: - for k,v in suppliers.iteritems(): + for k,v in suppliers.items(): f.write("%s\n" % k) def handleInv(j, invf, invl): @@ -113,7 +112,7 @@ def handleInv(j, invf, invl): # doc_num ourref accno custref salesperson ord_date tot_net tot_due # layout - lines # doc_num prod_code prod_desc prod_qty prod_price prod_unit prod_net - for acc,pages in j['parsed'].iteritems(): + for acc,pages in j['parsed'].items(): for page in pages: if len(page['tot_due'].strip()) > 0: invf.write("%6s %6s %7s %-12s %-20s %8s %10s %10s\n" % (page['doc_num'], page['ourref'], page['accno'], page['custref'], @@ -148,4 +147,4 @@ def identify(j): with open(os.path.expanduser('/tmp/inv'), 'w') as f: with open(os.path.expanduser('/tmp/invline'), 'w') as l: recover(f, l) - print 'done' + print('done') diff --git a/docparser.py b/docparser.py index 9457730..135a161 100755 --- a/docparser.py +++ b/docparser.py @@ -1,26 +1,26 @@ -#!/usr/bin/python +#!/usr/bin/env python3 import sys import os import itertools import collections -from StringIO import StringIO +from textutil import split_lines jobdir = os.path.expanduser("~/printerface/pickle/") import colorsys N=20 HSV_tuples = [(x*1.0/N, 0.5, 0.8) for x in range(N)] -colours = itertools.cycle(map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)) +colours = itertools.cycle([colorsys.hsv_to_rgb(*x) for x in HSV_tuples]) def field(col, r, c, w=10, h=1, t='??'): - col.append(dict(r=r,c=c,w=w,h=h,t=t,line=r,rgb=colours.next())) + col.append(dict(r=r,c=c,w=w,h=h,t=t,line=r,rgb=next(colours))) class DocParser(object): def parse(self, job): if job['templ']: mname = 'extract' + job['templ'].title() - lines = job['plain'].splitlines() + lines = split_lines(job['plain']) dims = (len(lines), max([len(line) for line in lines])) if hasattr(self, mname): fields, page_data = getattr(self, mname)(job, lines, dims) @@ -33,11 +33,12 @@ def parse(self, job): def extractCrednote(self, job, lines, dims): return self.extractInvoice(job, lines, dims) - def extractInvoice(self, job, lines, (rows,cols)): + def extractInvoice(self, job, lines, dims): + (rows, cols) = dims all_fields = [] page_data = collections.OrderedDict() - pages = (rows-48)/48 + pages = (rows-48)//48 for page in range(pages): line =(page+1) * 48 fs = [] @@ -83,11 +84,12 @@ def extractInvoice(self, job, lines, (rows,cols)): return (all_fields, page_data) - def extractDelnote(self, job, lines, (rows,cols)): + def extractDelnote(self, job, lines, dims): + (rows, cols) = dims all_fields = [] page_data = collections.OrderedDict() - pages = (rows-48)/48 + pages = (rows-48)//48 for page in range(pages): line =(page+1) * 48 fs = [] @@ -122,13 +124,14 @@ def extractDelnote(self, job, lines, (rows,cols)): return (all_fields, page_data) - def extractStatement(self, job, lines, (rows,cols)): + def extractStatement(self, job, lines, dims): + (rows, cols) = dims # any lines after line containing 'PRINT STATEMENT SUMMARY' should be ignored rows = min([rows] + [lnum for (lnum,text) in enumerate(lines) if 'PRINT STATEMENT SUMMARY' in text]) all_fields = [] page_data = collections.OrderedDict() - pages = (rows-51)/51 + pages = (rows-51)//51 for page in range(pages): line =(page+1) * 51 fs = [] @@ -169,11 +172,12 @@ def extractStatement(self, job, lines, (rows,cols)): return (all_fields, page_data) - def extractPurchase(self, job, lines, (rows,cols)): + def extractPurchase(self, job, lines, dims): + (rows, cols) = dims all_fields = [] page_data = collections.OrderedDict() - pages = (rows-48)/48 + pages = (rows-48)//48 for page in range(pages): line =(page+1) * 48 fs = [] @@ -204,11 +208,12 @@ def extractPurchase(self, job, lines, (rows,cols)): return (all_fields, page_data) - def extractRemittance(self, job, lines, (rows,cols)): + def extractRemittance(self, job, lines, dims): + (rows, cols) = dims all_fields = [] page_data = collections.OrderedDict() - pages = (rows-48)/48 + pages = (rows-48)//48 for page in range(pages): line =(page+1) * 48 fs = [] @@ -235,7 +240,8 @@ def extractRemittance(self, job, lines, (rows,cols)): return (all_fields, page_data) - def extractPicklist(self, job, lines, (rows,cols)): + def extractPicklist(self, job, lines, dims): + (rows, cols) = dims all_fields = [] page_data = collections.defaultdict(list) diff --git a/httpserver.py b/httpserver.py index 1f1ee7c..352843a 100644 --- a/httpserver.py +++ b/httpserver.py @@ -15,15 +15,16 @@ datamodel. """ -import asynchat, asyncore, socket, select, urllib -import posixpath, sys, cgi, cStringIO, os, traceback, shutil -import mimetools, time -import cgi +import asynchat, asyncore, socket +import posixpath, sys, io, os, traceback +import html +import time +import urllib.parse import mimetypes -try: - from cStringIO import StringIO -except ImportError: - from StringIO import StringIO + +# HTTP headers and the request line are latin-1 on the wire; bodies we generate are utf-8 +HEADER_ENCODING = 'latin-1' +BODY_ENCODING = 'utf-8' """HTTP server base class. @@ -40,15 +41,18 @@ class CaseInsensitiveDict(dict): """Dictionary with case-insensitive keys - Replacement for the deprecated mimetools.Message class + Replacement for the deprecated mimetools.Message class. infile is a binary file of header lines. """ def __init__(self, infile, *args): self._ci_dict = {} lines = infile.readlines() for line in lines: + line = line.decode(HEADER_ENCODING) + if ':' not in line: + continue k,v=line.split(":",1) self._ci_dict[k.lower()] = self[k] = v.strip() - self.headers = self.keys() + self.headers = list(self.keys()) def getheader(self,key,default=""): return self._ci_dict.get(key.lower(),default) @@ -77,8 +81,19 @@ def __contains__(self,key): DEFAULT_ERROR_CONTENT_TYPE = "text/html" -def _quote_html(html): - return html.replace("&", "&").replace("<", "<").replace(">", ">") +def _quote_html(text): + return text.replace("&", "&").replace("<", "<").replace(">", ">") + +def _body_file(f, ctype): + """Normalise whatever a path handler returned into (binary file object, content type). + Handlers return str (json, plain), bytes (mako output, pdf) or a binary file object.""" + if isinstance(f, str): + f = f.encode(BODY_ENCODING) + if isinstance(f, (bytes, bytearray)): + f = io.BytesIO(f) + if ctype.startswith('text/') and 'charset' not in ctype: + ctype += '; charset=' + BODY_ENCODING + return f, ctype class BaseHTTPRequestHandler(asynchat.async_chat): @@ -109,7 +124,7 @@ def parse_request(self, requestline): self.request_version = version = self.default_request_version self.close_connection = 1 - requestline = requestline.rstrip('\r\n') + requestline = requestline.decode(HEADER_ENCODING).rstrip('\r\n') self.requestline = requestline words = requestline.split() if len(words) == 3: @@ -150,10 +165,10 @@ def parse_request(self, requestline): return False querystring = dict() - qparts = path.split('?', 1); + qparts = path.split('?', 1) if len(qparts) > 1: path = qparts[0] - querystring = cgi.parse_qs(qparts[1]) + querystring = urllib.parse.parse_qs(qparts[1]) self.command, self.path, self.request_version, self.query_string = command, path, version, querystring # Examine the headers and look for a Connection directive @@ -196,7 +211,7 @@ def send_error(self, code, message=None): self.send_header('Connection', 'close') self.end_headers() if self.command != 'HEAD' and code >= 200 and code not in (204, 304): - self.push(content) + self.push(content.encode(BODY_ENCODING)) error_message_format = DEFAULT_ERROR_MESSAGE error_content_type = DEFAULT_ERROR_CONTENT_TYPE @@ -215,15 +230,14 @@ def send_response(self, code, message=None): else: message = '' if self.request_version != 'HTTP/0.9': - self.push("%s %d %s\r\n" % (self.protocol_version, code, message)) - # print (self.protocol_version, code, message) + self.push(("%s %d %s\r\n" % (self.protocol_version, code, message)).encode(HEADER_ENCODING, 'replace')) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string()) def send_header(self, keyword, value): """Send a MIME header.""" if self.request_version != 'HTTP/0.9': - self.push("%s: %s\r\n" % (keyword, value)) + self.push(("%s: %s\r\n" % (keyword, value)).encode(HEADER_ENCODING, 'replace')) if keyword.lower() == 'connection': if value.lower() == 'close': @@ -234,7 +248,7 @@ def send_header(self, keyword, value): def end_headers(self): """Send the blank line ending the MIME headers.""" if self.request_version != 'HTTP/0.9': - self.push("\r\n") + self.push(b"\r\n") def log_request(self, code='-', size='-'): """Log requests, called by send_response(). """ @@ -451,11 +465,7 @@ def write_headers(self, connection): if (handler): try: resp = ResponseGatherer() - (f, ctype) = handler(query_string=self.query_string, resp=resp) - if type(f) is str: - c = StringIO() - c.write(f) - f = c + (f, ctype) = _body_file(*handler(query_string=self.query_string, resp=resp)) self.send_response(200) resp.write_headers(self) self.send_header("Content-type", ctype) @@ -467,7 +477,7 @@ def write_headers(self, connection): return f except: tb = traceback.format_exc() - print tb + print(tb) self.send_error(500, "File not found") return None @@ -495,7 +505,7 @@ def write_headers(self, connection): f = open(path, 'rb') except IOError: tb = traceback.format_exc() - print tb + print(tb) self.send_error(404, "File not found") return None self.send_response(200) @@ -520,8 +530,8 @@ def list_directory(self, path): self.send_error(404, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) - f = StringIO() - displaypath = cgi.escape(urllib.unquote(self.path)) + f = io.StringIO() + displaypath = html.escape(urllib.parse.unquote(self.path)) f.write('') f.write("\nDirectory listing for %s\n" % displaypath) f.write("\n

Directory listing for %s

\n" % displaypath) @@ -537,10 +547,10 @@ def list_directory(self, path): displayname = name + "@" # Note: a link to a directory displays with @ and links with / f.write('
  • %s\n' - % (urllib.quote(linkname), cgi.escape(displayname))) + % (urllib.parse.quote(linkname), html.escape(displayname))) f.write("\n
    \n\n\n") - length = f.tell() - f.seek(0) + f = io.BytesIO(f.getvalue().encode(sys.getfilesystemencoding(), 'replace')) + length = len(f.getvalue()) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) @@ -559,9 +569,9 @@ def translate_path(self, path): # abandon query parameters path = path.split('?',1)[0] path = path.split('#',1)[0] - path = posixpath.normpath(urllib.unquote(path)) + path = posixpath.normpath(urllib.parse.unquote(path)) words = path.split('/') - words = filter(None, words) + words = [w for w in words if w] path = self.webroot for word in words: drive, word = os.path.splitdrive(word) @@ -620,9 +630,9 @@ def __init__(self,conn,addr, webroot=os.getcwd(), path_handlers={}): self.reset_terminator(); def reset_terminator(self): - self.set_terminator ('\r\n\r\n') + self.set_terminator (b'\r\n\r\n') self.found_terminator = self.handle_request_line - self.rfile = cStringIO.StringIO() + self.rfile = io.BytesIO() def collect_incoming_data(self,data): self.rfile.write(data) @@ -630,19 +640,14 @@ def collect_incoming_data(self,data): def do_POST(self): """Begins serving a POST request. The request data must be readable on a file-like object called self.rfile""" - ctype, pdict = cgi.parse_header(self.headers.getheader('content-type')) - postreq = cgi.FieldStorage(fp=self.rfile, - headers=self.headers, environ = {'REQUEST_METHOD':'POST'}, - keep_blank_values = 1) + # only urlencoded form bodies are understood; fields arrive as {name: [values]}, like query_string + body = self.rfile.getvalue().decode(BODY_ENCODING, 'replace') + postreq = urllib.parse.parse_qs(body, keep_blank_values=True) handler = self.handlers.get(self.path) if (handler): try: - (f, ctype) = handler(query_string=self.query_string, postreq=postreq) - if type(f) is str: - c = StringIO() - c.write(f) - f = c + (f, ctype) = _body_file(*handler(query_string=self.query_string, postreq=postreq)) self.send_response(200) self.send_header("Content-type", ctype) f.seek(0, os.SEEK_END) @@ -650,10 +655,12 @@ def do_POST(self): # self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() f.seek(0) - return f + self.push(f.read()) + f.close() + return None except: tb = traceback.format_exc() - print tb + print(tb) self.send_error(500, "File not found") return None else: @@ -671,7 +678,7 @@ def handle_request_line(self): bytesToRead = int(self.headers.getheader('content-length', '0')) if bytesToRead > 0: self.set_terminator(bytesToRead) - self.rfile = cStringIO.StringIO() + self.rfile = io.BytesIO() # control will be passed to a new found_terminator self.found_terminator = self.dispatch_handler @@ -697,11 +704,6 @@ def handle_error(self): traceback.print_exc(sys.stderr) self.close() - def log_message(self, format, *args): - sys.stdout.write("%s %s %s %s\n" % - (self.id,self.log_date_time_string(), self.address_string(), - format%args)) - def log_message(self, format, *args): sys.stdout.write("%s %s %s %s\n" % (self.id, self.log_date_time_string(), self.address_string(), format%args)) @@ -720,7 +722,7 @@ def __init__ (self, ip='', port=8081, webroot=os.getcwd(), handler=RequestHandle self.bind ((ip, port)) self.listen (100) - print "[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot) + print("[httpd] ToyHTTPServer running on port %s, serving from %s" % (port, self.webroot)) def handle_accept (self): try: @@ -735,9 +737,7 @@ def handle_accept (self): if __name__=="__main__": def about(query_string=''): - f = StringIO() - f.write("hi %s" % query_string) - return (f,'text/plain') + return ("hi %s" % query_string, 'text/plain') # launch the server on the specified port s = ToyHttpServer(port=8081, pathhandlers={'/about': about}) @@ -745,6 +745,6 @@ def about(query_string=''): try: while True: asyncore.loop(timeout=2, count=10) - print '[control] poll' + print('[control] poll') except KeyboardInterrupt: - print "Crtl+C pressed. Shutting down." + print("Crtl+C pressed. Shutting down.") diff --git a/lpdserver.py b/lpdserver.py index 151ab30..d3c9319 100644 --- a/lpdserver.py +++ b/lpdserver.py @@ -1,88 +1,92 @@ # Line Printer Daemon implementation, using asynchat # Chris Shucksmith 2013 -import asynchat, asyncore, socket, exceptions, os +import asynchat, asyncore, socket, os import sys +# LPD is a byte protocol and print data is 8-bit. Decode everything as latin-1 so that one byte is +# always one character (columns in the fixed-width documents must not shift) and so it round-trips. +ENCODING = 'latin-1' + (AwaitingCommand, NewJob, NewJobControl, NewJobData, EndOfFile ) = range(0,5) class LpdHandler(asynchat.async_chat): def __init__(self, sock, addr, controller): - try: - asynchat.async_chat.__init__(self, sock=sock) - except exceptions.TypeError: - # compat python 2.5.2 bugfix for http://bugs.python.org/issue1519 - asynchat.async_chat.__init__(self, conn=sock) + asynchat.async_chat.__init__(self, sock=sock) self.ibuffer = [] self.sm = AwaitingCommand - self.set_terminator("\n") + self.set_terminator(b"\n") self.sock = sock self.controller = controller self.id = "[lpd-%d]" % addr[1] print('%s installed LpdHandler' % self.id) - + def collect_incoming_data(self, data): self.ibuffer.append(data) print('%s collect_data - %d bytes' % (self.id, len(data))) def found_terminator(self): - chunk = self.ibuffer.pop(0) + # the terminator can arrive split over several recv()s, so gather every fragment + chunk = b''.join(self.ibuffer) + self.ibuffer = [] + cmd = chunk[:1] if self.sm == AwaitingCommand: # Main command verb - if chunk[0] == '\x02': - self.queue = chunk[1:] + if cmd == b'\x02': + self.queue = chunk[1:].decode(ENCODING) print('%s Incoming job to queue \'%s\'' % (self.id, self.queue)) - self.push('\x00') + self.push(b'\x00') self.sm = NewJob else: - print('%s unknown message type %d' + (self.id, self.ibuffer[0])) + print('%s unknown message type %r' % (self.id, cmd)) elif self.sm == NewJob: # Recieve Job - if chunk[0] == '\x02': # Subcommand - Control filename - sz,name = chunk[1:].split(' ', 1) + if cmd == b'\x02': # Subcommand - Control filename + sz,name = chunk[1:].decode(ENCODING).split(' ', 1) rdlength = int(sz) print('%s Incoming header: control file sz %d filename %s' % (self.id, rdlength,name)) self.sm = NewJobControl self.set_terminator(rdlength+1) # include the trailing null - self.push('\x00') - elif chunk[0] == '\x03': # Subcommand - Data filename - sz,name = chunk[1:].split(' ', 1) + self.push(b'\x00') + elif cmd == b'\x03': # Subcommand - Data filename + sz,name = chunk[1:].decode(ENCODING).split(' ', 1) rdlength = int(sz) print('%s incoming header: data file sz %d filename %s' % (self.id, rdlength,name)) self.sm = NewJobData - # windows seems to set a stupidly large length here and kill the socket to + # windows seems to set a stupidly large length here and kill the socket to # indicate eof. Handle either self.set_terminator(rdlength+1) # include the trailing null # self.set_terminator(None) # terminated by close of socket - self.push('\x00') + self.push(b'\x00') else: - print('%s recieve job unknown subcommand: 0x%x' % (self.id, chunk[0])) + print('%s recieve job unknown subcommand: %r' % (self.id, cmd)) elif self.sm == NewJobControl: # Recieve - Job Control file (null terminated) - self.controldata = dict([ (x[0], x[1:]) for x in chunk[:-1].split('\n') if len(x) > 1]) + self.controldata = dict([ (x[0], x[1:]) for x in chunk[:-1].decode(ENCODING).split('\n') if len(x) > 1]) print('%s control file: %s' % (self.id, repr(self.controldata))) - self.push('\x00') + self.push(b'\x00') self.sm = NewJob - self.set_terminator("\n") + self.set_terminator(b"\n") elif self.sm == NewJobData: # Recieve - Job Data file (terminated by close) # Windows NT4 lpr sends a well formed size, hits this code print('%s end of data file' % self.id) # put the chunk back on the ibuffer for dispatch() self.ibuffer.insert(0, chunk) self.sm = EndOfFile - self.push('\x00') + self.push(b'\x00') self.close_when_done() self.dispatch() else: - print('%s Unknown state, woken up by terminator, buffer was: %s' % (self.id, repr(self.ibuffer))) + print('%s Unknown state, woken up by terminator, chunk was: %s' % (self.id, repr(chunk))) self.close_when_done() + def handle_close(self): print('%s handle_close' % (self.id)) if self.sm == NewJobData: print('%s data file: %s' % (self.id, repr(self.ibuffer)[:100])) - # calling push() after the client has closed the socket will re-invoke handle_close, so + # calling push() after the client has closed the socket will re-invoke handle_close, so # switch to terminal state to avoid inf recursion self.sm = EndOfFile self.dispatch() - self.push('\x00') + self.push(b'\x00') self.close_when_done() elif self.sm == EndOfFile: self.close() @@ -91,13 +95,13 @@ def handle_close(self): self.close() def dispatch(self): - data = ''.join(self.ibuffer) + data = b''.join(self.ibuffer).decode(ENCODING) # log exceptions during dispatch so that we get the thread back to perform socket clean up try: print('%s dispatching' % (self.id)) self.controller(self.queue, self.sock.getpeername(), self.sock.getsockname(), self.controldata, data) except Exception as e: - print('LPD dispatch of print job threw exception: %s', sys.exc_info()[0]) + print('LPD dispatch of print job threw exception: %s' % sys.exc_info()[0]) print(e) sys.stdout.flush() print('%s dispatch complete' % (self.id)) diff --git a/mailer.py b/mailer.py index 06c9f24..e52c181 100644 --- a/mailer.py +++ b/mailer.py @@ -5,43 +5,43 @@ # Import smtplib for the actual sending function import smtplib from email.mime.text import MIMEText -from email.MIMEMultipart import MIMEMultipart -from email.MIMEBase import MIMEBase -from email import Encoders +from email.mime.multipart import MIMEMultipart +from email.mime.base import MIMEBase +from email import encoders +from settings import config, HOME +from textutil import load_user_pickles, PICKLE_PROTOCOL # http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python import datetime -import ConfigParser, os, threading -import Queue +import os, threading +import queue import traceback import pickle -pickle_file = '~/printerface/mailer.pickle' - -config = ConfigParser.ConfigParser() -config.read('defaults.cfg') -config.read(os.path.expanduser('~/printerface/email.cfg')) +pickle_file = os.path.join(HOME, 'mailer.pickle') class JobMailer(object): def __init__(self, queuesz=10): - self.queue = Queue.Queue(queuesz) - self.thread = threading.Thread(target=self.run) - self.thread.daemon = True - self.thread.start() + self.queue = queue.Queue(queuesz) self.results = [] - self.resultLimit = config.get('Gmail', 'result_count') + self.resultLimit = config.getint('Gmail', 'result_count') try: - with open(os.path.expanduser(pickle_file), 'rb') as f: - p = pickle.Unpickler(f) - self.results = p.load() + with open(pickle_file, 'rb') as f: + [self.results] = load_user_pickles(f) + except FileNotFoundError: + pass except: traceback.print_exc() while len(self.results) > self.resultLimit: self.results.pop() + self.thread = threading.Thread(target=self.run) + self.thread.daemon = True + self.thread.start() + def append(self, job): job['added'] = datetime.datetime.now() job['completed']=None @@ -65,7 +65,7 @@ def run(self): work['error'] = None except Exception as e: - print 'mailq: failed to send email: ' + repr(e) + print('mailq: failed to send email: ' + repr(e)) work['completed'] = datetime.datetime.now() work['error'] = repr(e) @@ -77,13 +77,13 @@ def run(self): self.pickleResults() - except Queue.Empty: + except queue.Empty: print('mailq: idling for jobs') def pickleResults(self): try: - with open(os.path.expanduser(pickle_file), 'wb') as f: - p = pickle.Pickler(f) + with open(pickle_file, 'wb') as f: + p = pickle.Pickler(f, protocol=PICKLE_PROTOCOL) p.dump(self.results) except Exception as e: traceback.print_exc() @@ -105,7 +105,7 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail", part = MIMEBase('application', "octet-stream") part.set_payload(file.read()) - Encoders.encode_base64(part) + encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) @@ -133,6 +133,6 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail", print(mailq.results) - print 'done' + print('done') diff --git a/main.py b/main.py index 3b24d5c..e649410 100755 --- a/main.py +++ b/main.py @@ -1,6 +1,4 @@ -#!/usr/bin/env python2.7 - -from __future__ import with_statement +#!/usr/bin/env python3.11 from mako.template import Template from mako.lookup import TemplateLookup @@ -15,21 +13,19 @@ from stationary import DocFormatter from printing import getPrinters, printFile -import sys, pickle, ConfigParser -from StringIO import StringIO +import sys, pickle +from io import StringIO import collections import traceback import json import time import pytz +from settings import config, HOME +from textutil import split_lines, load_job_pickle, load_user_pickles, PICKLE_PROTOCOL -config = ConfigParser.ConfigParser() -config.readfp(open(os.path.expanduser('defaults.cfg'))) -config.read(os.path.expanduser('~/printerface/email.cfg')) - -email_pickle = os.path.expanduser('~/printerface/email.pickle') +email_pickle = os.path.join(HOME, 'email.pickle') -data_dir = os.path.expanduser("~/printerface/data/") +data_dir = os.path.join(HOME, 'data') + os.sep jobdir = os.path.join(data_dir, 'pickle') pdfdir = os.path.join(data_dir, 'pdf/') @@ -60,14 +56,10 @@ def saveJob(queue, local, remote, control, data): subdir = ts.strftime('%Y%m') d = {'queue':queue, 'from':repr(local), 'to':repr(remote), 'control':control, 'data':data, 'ts': ts, 'name':jobname} - try: - os.makedirs(os.path.join(jobdir, subdir)) - except: - pass + os.makedirs(os.path.join(jobdir, subdir), exist_ok=True) - f = file(os.path.join(jobdir, subdir, jobname), "wb") - pickle.dump(d, f) - f.close() + with open(os.path.join(jobdir, subdir, jobname), "wb") as f: + pickle.dump(d, f, protocol=PICKLE_PROTOCOL) cleanJob(d) autoPrint(d) @@ -81,14 +73,14 @@ def autoPrint(job): if job['autoprint']: printer = job['autoprint'] for (groupnum, gname) in enumerate(job['groupkey']): - for (dockey, doc) in job['groupfiles'].iteritems(): + for (dockey, doc) in job['groupfiles'].items(): if doc: printFile(pdfdir + doc, printer ) print( 'auto printing: Document %s sent to printer %s' % (doc, printer)) def saveEmails(): with open(email_pickle, 'wb') as f: - p = pickle.Pickler(f) + p = pickle.Pickler(f, protocol=PICKLE_PROTOCOL) p.dump(email_addresses) p.dump(email_accounts) p.dump(email_template) @@ -98,11 +90,10 @@ def recover(): global email_template try: with open(email_pickle, 'rb') as f: - p = pickle.Unpickler(f) - for (k,v) in p.load().iteritems(): + (addresses, accounts, email_template) = load_user_pickles(f, 3) + for (k,v) in addresses.items(): email_addresses[k].update(v) - email_accounts.update(p.load()) - email_template = p.load() + email_accounts.update(accounts) print('recovered emails: %s' % email_addresses) print('recovered accounts: %s' % email_accounts) @@ -118,8 +109,8 @@ def recover(): p = os.path.join(jobdir, yyyymmdir, x) if not os.path.isfile(p): continue try: - with file(p, "rb") as f: - s = pickle.load(f) + with open(p, "rb") as f: + s = load_job_pickle(f) s['name'] = x; jobs.append(s) except Exception as e: @@ -130,7 +121,9 @@ def recover(): for j in jobs: cleanJob(j) -control_char_re = re.compile('[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"')) +# re.ASCII: python 2 str patterns only ever treated ASCII as word/space characters, so any 8-bit +# character in the print data becomes a space. Without it \x85 etc. count as whitespace and survive. +control_char_re = re.compile(r'[^\w\s%s_\'=/]' % re.escape('.*+()-\\;:,#?%$^&!<>|`"'), re.ASCII) def cleanJob(j): print(' recovering %s' % j['name']) @@ -139,10 +132,10 @@ def cleanJob(j): # handle input j['plain'] = control_char_re.sub(' ', j['data']) - summary = re.compile('[^\w\s]').sub('', j['data']) + summary = re.compile(r'[^\w\s]', re.ASCII).sub('', j['data']) for r in summary_regexps: summary = r.sub(' ', summary) - summary = re.compile('\s+').sub(' ', summary) + summary = re.compile(r'\s+', re.ASCII).sub(' ', summary) summary = summary.strip()[0:120] j['summary'] = summary @@ -162,7 +155,7 @@ def cleanJob(j): if not j['colouring']: del j['colouring'] if j['parsed']: - for y in j['parsed'].itervalues(): + for y in j['parsed'].values(): for x in y: acc = None addr = None @@ -187,7 +180,7 @@ def cleanJob(j): # groups {('all'): p}, ('all') (j['groupfiles'], j['groupkey']) = formatter.format(j) - #for f in j['groupfiles'].itervalues(): + #for f in j['groupfiles'].values(): # from subprocess import call # proc = ['convert','-size','150x150','%s[0]' % f, '%s.png' % f] # print(proc) @@ -214,11 +207,11 @@ def identify(j): def home(query_string='', resp=None): email_fails = sum([1 for x in mailqueue.results if x['error']]) - account = sum([ 1 for k in email_accounts.iterkeys() if len(email_addresses[k]) > 0 ]), len(email_accounts.keys()) + account = sum([ 1 for k in email_accounts if len(email_addresses[k]) > 0 ]), len(email_accounts.keys()) return template_lookup.get_template("/home.html").render(email_fails=email_fails, account=account), 'text/html' def getrows_byslice(seq, rowlen): - for start in xrange(0, len(seq), rowlen): + for start in range(0, len(seq), rowlen): yield seq[start:start+rowlen] def recent(query_string=dict(), resp=None): @@ -259,7 +252,7 @@ def job(query_string=dict(), resp=None): 'doctype': job.get('doctype'), 'autofmt': job.get('autofmt'), 'stationary': - dict([ (' '.join(k), '{base}/pdf/{pdf}'.format(base=base_uri, pdf=v)) for k,v in job.get('groupfiles', {}).iteritems() ]) + 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' @@ -295,8 +288,8 @@ def settings_email(query_string='', postreq=None, resp=None): pass email_list = [] - for key in sorted(email_accounts.iterkeys()): - email_list.append( (key, email_accounts[key], email_addresses[key].iteritems()) ) + for key in sorted(email_accounts): + email_list.append( (key, email_accounts[key], list(email_addresses[key].items())) ) return ( template_lookup.get_template("/settings_email.html").render(emails=email_list, warning=warning), 'text/html') @@ -327,7 +320,7 @@ def printfn(query_string='', resp=None): def pdf(query_string=dict(), resp=None): job = getJob(query_string) - default_key = job['groupfiles'].iterkeys().next()[0] + default_key = next(iter(job['groupfiles']))[0] key = query_string.get('key', [default_key])[0] email_dest = email_addresses.get(key, {}) email_outcome, email_error = None, None @@ -390,12 +383,12 @@ def getJob(query_string, returnLast=False): def getJobFile(query_string, job=None): if not job: job = getJob(query_string) - default_key = job['groupfiles'].iterkeys().next()[0] + default_key = next(iter(job['groupfiles']))[0] key = query_string.get('key', [default_key])[0] docf = None for (groupnum, gname) in enumerate(job['groupkey']): - for (dockey,doc) in job['groupfiles'].iteritems(): + for (dockey,doc) in job['groupfiles'].items(): if dockey[groupnum] == key: docf = doc @@ -414,7 +407,7 @@ def debug(query_string=dict(), resp=None): colouring = job.get('colouring', []) - lines = job['plain'].splitlines() + lines = split_lines(job['plain']) (rows, cols) = (len(lines), max([len(line) for line in lines])) cols = max([cols] + [c['c']+c['w'] for c in colouring]) @@ -427,7 +420,7 @@ def debug(query_string=dict(), resp=None): for col in range(c['c'], c['c']+c['w']): high[row][col] = c - chunks10 = (cols+9)/10 + chunks10 = (cols+9)//10 f = StringIO() f.write(' ' + ''.join(["%-10d" % (d*10) for d in range(chunks10)])) f.write('\n ' + ('0123456789' * chunks10)) @@ -457,32 +450,31 @@ def htmlcol(rgb): return ( template_lookup.get_template("/debug.html").render( job=job, rows=rows, cols=cols, coloured_plaintext=f.getvalue(), pformatted=pformatted), 'text/html') +path_handlers = { + '/recent': recent, + '/home':home, + '/debug':debug, + '/raw':raw, + '/job': job, + '/printers':printers, + '/pdf':pdf, + '/pdf_file': pdf_file, + '/sent':sent, + '/print' : printfn, + '/plaintext':plain, + '/settings/email':settings_email, + '/settings/template':settings_template + } + if __name__=="__main__": # launch the server on the specified port for x in [jobdir, pdfdir]: - try: - os.makedirs(x) - except: - pass + os.makedirs(x, exist_ok=True) recover() s = LpdServer(saveJob, ip='', port=int(config.get('Main', 'lpd_port'))) - ToyHttpServer(port=int(config.get('Main', 'http_port')), pathhandlers={ - '/recent': recent, - '/home':home, - '/debug':debug, - '/raw':raw, - '/job': job, - '/printers':printers, - '/pdf':pdf, - '/pdf_file': pdf_file, - '/sent':sent, - '/print' : printfn, - '/plaintext':plain, - '/settings/email':settings_email, - '/settings/template':settings_template - }, webroot=web_dir) + ToyHttpServer(port=int(config.get('Main', 'http_port')), pathhandlers=path_handlers, webroot=web_dir) try: while True: asyncore.loop(timeout=1, count=10) @@ -492,7 +484,7 @@ def htmlcol(rgb): except KeyboardInterrupt: print("Crtl+C pressed. Shutting down.") except: - print("Terminating: Unexpected error: %s", sys.exc_info()[0]) + print("Terminating: Unexpected error: %s" % sys.exc_info()[0]) sys.stdout.flush() raise diff --git a/printing.py b/printing.py index f71f8aa..9d799fe 100644 --- a/printing.py +++ b/printing.py @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/env python3 import sys import subprocess @@ -6,15 +6,15 @@ def getPrinters(): global printers - if not sys.platform == "linux2": + if not sys.platform.startswith("linux"): return ['default'] if len(printers) > 0: return printers try: - process = subprocess.Popen(["lpstat", "-a"], stdout=subprocess.PIPE) + process = subprocess.Popen(["lpstat", "-a"], stdout=subprocess.PIPE, universal_newlines=True) result = process.communicate()[0].strip() # KONICA_bizhub_192.168.12.10 accepting requests since Sun 16 Dec 2012 07:43:59 PM GMT print(result) - printers = [x.split(' ')[0] for x in result.split('\n')] + printers = [x.split(' ')[0] for x in result.split('\n') if x.strip()] print('[print] printers=%s' % repr(printers)) except OSError as e: print('[print] %s' % repr(e)) diff --git a/settings.py b/settings.py new file mode 100644 index 0000000..8ec57f6 --- /dev/null +++ b/settings.py @@ -0,0 +1,19 @@ +# Locations and configuration shared by main, mailer and stationary. +# +# 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 os + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +HOME = os.path.expanduser(os.environ.get('PRINTERFACE_HOME', '~/printerface')) + +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')) + return config + +config = load_config() diff --git a/stationary.py b/stationary.py index 0f6f1f8..6023ec6 100644 --- a/stationary.py +++ b/stationary.py @@ -1,13 +1,12 @@ -import ConfigParser import reportlab import os +import shutil import sys from reportlab.pdfgen import canvas -config = ConfigParser.ConfigParser() -config.read('defaults.cfg') -config.read(os.path.expanduser('~/printerface/email.cfg')) +from settings import config +from textutil import split_lines from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4, landscape @@ -62,7 +61,7 @@ def topBox(c, x, y, title="Title", content="The quick brown", w=2*cm, h=2.0*cm, c.setFont("Helvetica", hfontsz) lineheight = hfontsz * 1.2 if align=='c': - for lineno, text in enumerate(title.splitlines()): + for lineno, text in enumerate(split_lines(title)): c.drawCentredString(w*0.5, -.33*cm*(lineno+1), text) else: c.drawString(0.8*cm, -.33*cm, title) @@ -438,10 +437,7 @@ def genericPage(c, data, title=None, fontsz=7, landsc=False, overlay=None, decor class DocFormatter(object): def __init__(self, pdfdir): self.jobdir = pdfdir - try: - os.makedirs(jobdir) - except: - pass + os.makedirs(self.jobdir, exist_ok=True) def format(self, ctx): mname = 'write' + ctx['templ'].title() @@ -458,7 +454,7 @@ def plainFormat(self, ctx): def writeInvoice(self, ctx ): rendered_pdfs = {} - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc)) self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) @@ -474,7 +470,7 @@ def writeInvoice(self, ctx ): c = canvas.Canvas(p, pagesize=A4) pages_by_docnum = dict() - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for page in v: pages_by_docnum.setdefault(page['doc_num'], []).append(page) for k in reversed(sorted(pages_by_docnum.keys())): @@ -492,7 +488,7 @@ def writePicklist(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for page in v: data = page['data'] @@ -524,7 +520,7 @@ def writeRaw(self, ctx): c = canvas.Canvas(p, pagesize=A4) landsc, fontsz, row, cols = ctx['autofmt'] - pages = filter(None, ctx['plain'].strip().split("\f")) + pages = [p for p in ctx['plain'].strip().split("\f") if p] for page in pages: genericPage(c, page, title=None, fontsz=fontsz, landsc=landsc) @@ -554,7 +550,7 @@ def writeCrednote(self, ctx): def writeStatement(self, ctx): rendered_pdfs = {} - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc)) self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) @@ -569,7 +565,7 @@ def writeStatement(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for page in v: statementPage(c, page, 'ACCOUNTS COPY') @@ -585,7 +581,7 @@ def writeDelnote(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for mark in ['CUSTOMER COPY', 'ACCOUNTS COPY']: for page in v: deliveryNotePage(c, page, mark) @@ -598,7 +594,7 @@ def writeRemittance(self, ctx): rendered_pdfs = {} - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s.pdf" % (ctx['name'], acc)) self.create_dirs(p) @@ -614,7 +610,7 @@ def writeRemittance(self, ctx): self.create_dirs(p) c = canvas.Canvas(p, pagesize=A4) - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for page in v: remittancePage(c, page, 'ACCOUNTS COPY') @@ -629,7 +625,7 @@ def writePurchase(self, ctx): rendered_pdfs = {} - for (acc,v) in ctx['parsed'].iteritems(): + for (acc,v) in ctx['parsed'].items(): for (bundle, marks) in [ ( '', ['SUPPLIER COPY']), ('-transport', ['TRANSPORTER COPY']), ('-admin', ['MASTER COPY', 'BOOKING IN COPY', 'PRE LOCATION COPY']) ]: p = os.path.join(self.jobdir, ctx['ts'].strftime('%Y'), acc, "%s-%s%s.pdf" % (ctx['name'], acc, bundle)) @@ -664,11 +660,11 @@ def writePurchase(self, ctx): # port 12 55 76 # port 13 51 71 def getBestPageFormat(self, plaintext): - pages = filter(None, plaintext.strip().split("\f")) + pages = [p for p in plaintext.strip().split("\f") if p] worst_rows, worst_cols = 0, 0 for pi, page in enumerate(pages): - lines = page.splitlines() + lines = split_lines(page) (rows, cols) = (len(lines), max([len(line) for line in lines])) # print (' page %d rows %d cols %d' % (pi, rows, cols)) worst_cols = max(worst_cols, cols) @@ -695,7 +691,7 @@ def getBestPageFormat(self, plaintext): (True, 6 , 78, 224), ] - soln = filter( lambda x: x[2] > worst_rows and x[3] > worst_cols, a4_cand) + soln = [x for x in a4_cand if x[2] > worst_rows and x[3] > worst_cols] if len(soln): sol = soln[0] # print(' solution for pages=%d worst r=%d c=%d is %s' % (len(pages), worst_rows, worst_cols, sol)) @@ -707,9 +703,10 @@ def getBestPageFormat(self, plaintext): class TestStationary(unittest.TestCase): def setUp(self): - pdir = os.path.expanduser("~/printerface/") - jobdir = pdir + 'pdf/' - self.formatter = DocFormatter(jobdir) + import tempfile + self.tmp = tempfile.mkdtemp(prefix='printerface-test-') + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + self.formatter = DocFormatter(os.path.join(self.tmp, 'pdf') + os.sep) self.chuff = dict(date='04/10/12', doc_num='731/289073', @@ -758,23 +755,23 @@ def test_delnote(self): amt_encl='amt_encl', ) - s.append( dict(order.items() + self.chuff.items())) + s.append( {**order, **self.chuff}) ctx['parsed'] = { 'SMP109': s} p = self.formatter.format(ctx) - self.assertEquals( ({('accounts',): '2014/accounts/blahdel-accounts.pdf'}, ('type',) ), p) + self.assertEqual( ({('accounts',): '2014/accounts/blahdel-accounts.pdf'}, ('type',) ), p) ctx['templ'] = 'purchase' ctx['name'] = 'blahpurch' p = self.formatter.format(ctx) - self.assertEquals( ({ ('SMP109',): '2014/SMP109/blahpurch-SMP109.pdf', + self.assertEqual( ({ ('SMP109',): '2014/SMP109/blahpurch-SMP109.pdf', ('SMP109-admin',): '2014/SMP109/blahpurch-SMP109-admin.pdf', ('SMP109-transport',): '2014/SMP109/blahpurch-SMP109-transport.pdf'}, ('type',) ), p) ctx['templ'] = 'remittance' ctx['name'] = 'blahremit' p = self.formatter.format(ctx) - self.assertEquals( ({('SMP109',): '2014/SMP109/blahremit-SMP109.pdf', + self.assertEqual( ({('SMP109',): '2014/SMP109/blahremit-SMP109.pdf', ('accounts',): '2014/accounts/blahremit-accounts.pdf'}, ('Group',) ), p) def test_statement(self): @@ -813,11 +810,11 @@ def test_statement(self): age_due="16.00" ) - s.append( dict(order.items() + self.chuff.items())) + s.append( {**order, **self.chuff}) ctx['parsed'] = { 'SMP109': s} p = self.formatter.format(ctx) - self.assertEquals( ({('SMP109',): '2014/SMP109/blahstate-SMP109.pdf', ('accounts',): '2014/accounts/blahstate-accounts.pdf'}, ('Group',) ), p) + self.assertEqual( ({('SMP109',): '2014/SMP109/blahstate-SMP109.pdf', ('accounts',): '2014/accounts/blahstate-accounts.pdf'}, ('Group',) ), p) def test_cnote(self): # CREDIT NOTE / INVOICE paperwork @@ -849,10 +846,10 @@ def test_cnote(self): prod_net="1499.40\n"*sz, prod_vcode="5\n"*sz ) - s.append( dict(order.items() + self.chuff.items() + extra.items())) + s.append( {**order, **self.chuff, **extra}) ctx['parsed'] = { 'SMP109': s} p = self.formatter.format(ctx) - self.assertEquals( ({('SMP109',): '2014/SMP109/blahcn-SMP109.pdf', ('accounts',): '2014/accounts/blahcn-accounts.pdf'}, ('Group',) ), p) + self.assertEqual( ({('SMP109',): '2014/SMP109/blahcn-SMP109.pdf', ('accounts',): '2014/accounts/blahcn-accounts.pdf'}, ('Group',) ), p) def test_picklist(self): ctx = {} @@ -865,16 +862,16 @@ def test_picklist(self): {'data': 'fluff '*22, 'hdr': 'Picking list 5342', 'dt': 'Monday 03/12/18', 'page': 'PAGE 1'} ]} p = self.formatter.format(ctx) - self.assertEquals( ({('pick',): 'raw/201403/pick-a-pick.pdf'}, ('Group',) ), p) + self.assertEqual( ({('pick',): 'raw/201403/pick-a-pick.pdf'}, ('Group',) ), p) def test_calibrate(self): # test document to calibrate width/height fontsize matrix cols = 240 rows = 120 - import StringIO - chunks10 = (cols+9)/10 - f = StringIO.StringIO() + import io + chunks10 = (cols+9)//10 + f = io.StringIO() f.write('' + ''.join(["%-10d" % (d*10) for d in range(chunks10)])) f.write('\n' + ('0123456789' * chunks10)) for row in range(2,rows): @@ -888,9 +885,9 @@ def test_calibrate(self): p = self.formatter.format(ctx) def test_rawformat(self): - self.assertEquals( (False, 13,51,71), self.formatter.getBestPageFormat('ABCDEF') ) - self.assertEquals( (True, 13,35,102), self.formatter.getBestPageFormat('test'*20) ) - self.assertEquals( (False, 8, 83,115), self.formatter.getBestPageFormat('ABCDEF\n'*80) ) + self.assertEqual( (False, 13,51,71), self.formatter.getBestPageFormat('ABCDEF') ) + self.assertEqual( (True, 13,35,102), self.formatter.getBestPageFormat('test'*20) ) + self.assertEqual( (False, 8, 83,115), self.formatter.getBestPageFormat('ABCDEF\n'*80) ) ctx = {} ctx['templ'] = 'raw' @@ -900,7 +897,7 @@ def test_rawformat(self): ctx['plain'] = 'test12 ' * 20 ctx['autofmt'] = self.formatter.getBestPageFormat(ctx['plain']) p = self.formatter.format(ctx) - self.assertEquals( ({('plain',): 'raw/201402/rawtest-plain.pdf'}, ('Type',) ), p) + self.assertEqual( ({('plain',): 'raw/201402/rawtest-plain.pdf'}, ('Type',) ), p) def test_plainformat(self): ctx = {} @@ -909,7 +906,7 @@ def test_plainformat(self): ctx['ts'] = datetime(2014, 3, 4, 20, 53, 0, 0) ctx['autofmt'] = self.formatter.getBestPageFormat(ctx['plain']) p = self.formatter.plainFormat(ctx) - self.assertEquals( ({('plain',): 'raw/201403/rawtest2-plain.pdf'}, ('Type',) ), p) + self.assertEqual( ({('plain',): 'raw/201403/rawtest2-plain.pdf'}, ('Type',) ), p) if __name__=="__main__": unittest.main() diff --git a/textutil.py b/textutil.py new file mode 100644 index 0000000..20fb010 --- /dev/null +++ b/textutil.py @@ -0,0 +1,91 @@ +# Helpers that pin down text semantics which differ between python 2 str and python 3 str. +import re +import pickle +import unittest + +# Pickles written during the cutover use protocol 2 so that the previous python 2.7 release can still +# read anything written by python 3 if we have to roll back. Remove once rollback is no longer needed. +PICKLE_PROTOCOL = 2 + +# Python 2 str.splitlines() split on \n, \r and \r\n only. Python 3 str.splitlines() also splits on +# \f \v \x1c-\x1e \x85 
 
. The parsers address fixed rows and rely on \f surviving inside +# a line (it marks page breaks), so we must keep the python 2 behaviour. +_eol_re = re.compile(r'\r\n|\r|\n') + +def split_lines(s): + lines = _eol_re.split(s) + if lines and lines[-1] == '': + lines.pop() + return lines + +def load_job_pickle(f): + """Load a print job pickle. Python 2 'str' values were raw 8-bit bytes (the LPD payload); latin-1 + maps each byte to one character, matching lpdserver.ENCODING. Also loads datetimes.""" + return pickle.load(f, encoding='latin-1') + +def _text(b): + try: + return b.decode('utf-8') + except UnicodeDecodeError: + return b.decode('latin-1') + +def decode_bytes(obj): + """Recursively turn the bytes python 2 'str' objects load as into text. Values entered through the web + forms (contact names, email subjects) were utf-8 encoded. Text already written by python 3 is untouched. + Containers are updated in place so that defaultdict and friends keep their type.""" + if isinstance(obj, bytes): + return _text(obj) + if isinstance(obj, dict): + items = [(decode_bytes(k), decode_bytes(v)) for k, v in obj.items()] + obj.clear() + obj.update(items) + elif isinstance(obj, list): + obj[:] = [decode_bytes(x) for x in obj] + elif isinstance(obj, tuple): + return type(obj)(decode_bytes(x) for x in obj) if type(obj) is tuple else obj + elif isinstance(obj, (set, frozenset)): + return type(obj)(decode_bytes(x) for x in obj) + return obj + +def load_user_pickles(f, count=1): + """Load `count` consecutive pickles holding user entered data (email.pickle, mailer.pickle)""" + u = pickle.Unpickler(f, encoding='bytes') + return [decode_bytes(u.load()) for _ in range(count)] + +class TestTextUtil(unittest.TestCase): + def test_split_lines(self): + self.assertEqual(['a', 'b'], split_lines('a\nb')) + self.assertEqual(['a', 'b'], split_lines('a\r\nb\n')) + self.assertEqual(['a', '', 'b'], split_lines('a\n\nb')) + self.assertEqual([], split_lines('')) + self.assertEqual(['a\x0cb'], split_lines('a\x0cb')) + self.assertEqual(['a\x0bb\x85c\x1cd'], split_lines('a\x0bb\x85c\x1cd')) + + # what python 2.7 pickle.dump(..., protocol 0) wrote for {'ts': datetime, 'data': 'caf\xe9 \x0c'} + PY2_JOB = b"(dp0\nS'ts'\np1\ncdatetime\ndatetime\np2\n(S'\\x07\\xde\\x03\\x04\\x14\\x35\\x00\\x00\\x00\\x00'\ntp3\nRp4\nsS'data'\np5\nS'caf\\xe9 \\x0c'\np6\ns." + + def test_load_job_pickle_py2(self): + import io, datetime + d = load_job_pickle(io.BytesIO(self.PY2_JOB)) + self.assertEqual(datetime.datetime(2014, 3, 4, 20, 53), d['ts']) + self.assertEqual('caf\xe9 \x0c', d['data']) + + def test_user_pickles_py2_utf8(self): + import io, collections + # {'ACC': {'a@b.c': 'Jos\xc3\xa9'}} as python 2 str (utf-8 bytes from a web form), then a py3 style text value + raw = b"(dp0\nS'ACC'\np1\n(dp2\nS'a@b.c'\np3\nS'Jos\\xc3\\xa9'\np4\nss." + [d] = load_user_pickles(io.BytesIO(raw)) + self.assertEqual({'ACC': {'a@b.c': 'Jos\xe9'}}, d) + dd = collections.defaultdict(dict, ACC={b'x': b'\xff\xfe', 'y': 'caf\xe9'}) + out = decode_bytes(dd) + self.assertIsInstance(out, collections.defaultdict) + self.assertEqual({'x': '\xff\xfe', 'y': 'caf\xe9'}, out['ACC']) + + def test_pickle_roundtrip_protocol2(self): + import io, datetime + d = {'ts': datetime.datetime(2014, 3, 4, 20, 53), 'data': 'caf\xe9'} + buf = io.BytesIO(); pickle.dump(d, buf, protocol=PICKLE_PROTOCOL); buf.seek(0) + self.assertEqual(d, load_job_pickle(buf)) + +if __name__ == "__main__": + unittest.main() diff --git a/web/debug.html b/web/debug.html index a4b4575..b42bdcf 100644 --- a/web/debug.html +++ b/web/debug.html @@ -23,7 +23,7 @@

    PDF stationary output

    % if job.get('groupfiles', None):

    keys: ${job['groupkey']} - % for k,v in job['groupfiles'].iteritems(): + % for k,v in job['groupfiles'].items(): diff --git a/web/pdf.html b/web/pdf.html index 75cd0b1..997a7f2 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -79,8 +79,8 @@

    Compose Email

    - % for (em,cn) in email_dest.iteritems(): - + % for (em,cn) in email_dest.items(): + % endfor
    diff --git a/web/sent.html b/web/sent.html index 7846bbc..64f80cf 100644 --- a/web/sent.html +++ b/web/sent.html @@ -12,7 +12,7 @@

    Sent Items

    % else: % endif - + % endfor
    ${k}${v}
    ${'
    '.join(p['to'])}
    ${p['subject'].decode('utf-8')}${p['added']}${p['completed']}${p['error']}${'
    '.join(p['to'])}
    ${p['subject']}${p['added']}${p['completed']}${p['error']}
    diff --git a/web/settings_email.html b/web/settings_email.html index 3c77c02..b6925cc 100644 --- a/web/settings_email.html +++ b/web/settings_email.html @@ -44,10 +44,10 @@

    Existing Entries

    % endif % for (em,cn) in addresses: -
    + - ${cn.decode('utf-8')} ${em} + ${cn} ${em}
    From 2070dd55b62728e1e5de32d3c9b75139ec19e58a Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Wed, 18 Nov 2026 16:22:18 +0000 Subject: [PATCH 03/31] Add end to end tests: RFC1179 client -> LPD -> parse -> PDF -> HTTP Runs against a scratch directory; stationary tests no longer write to ~/printerface. Co-Authored-By: Claude Sonnet 5.5 --- test_integration.py | 227 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 test_integration.py diff --git a/test_integration.py b/test_integration.py new file mode 100644 index 0000000..fd35d33 --- /dev/null +++ b/test_integration.py @@ -0,0 +1,227 @@ +# End to end tests: a real RFC 1179 client -> LpdServer -> main.saveJob -> parse -> PDF, then read back +# over HTTP. Runs against a throwaway PRINTERFACE_HOME, never ~/printerface. +import asyncore +import http.client +import json +import os +import pickle +import shutil +import socket +import tempfile +import threading +import time +import unittest + +import main +import mailer +from stationary import DocFormatter +from lpdserver import LpdServer +from httpserver import ToyHttpServer +from textutil import split_lines + +def put(lines, row, col, text): + for i, part in enumerate(text.split('\n')): + line = lines[row + i] + lines[row + i] = line[:col] + part + line[col + len(part):] + +def make_invoice(doc_num='12345', acc='ACC001', pages=2): + """A synthetic Invoice print: 48 blank lines, then 48 lines per page. Each page ends in a form feed, + and the totals carry an 8-bit pound sign as the Windows print driver sends it.""" + lines = [' ' * 130 for _ in range(48 * (pages + 1))] + for p in range(pages): + base = (p + 1) * 48 + put(lines, base + 0, 0, 'INVOICE') + put(lines, base + 0, 95, '01/10/26') + put(lines, base + 2, 95, 'Page %d' % (p + 1)) + put(lines, base + 4, 95, doc_num) + put(lines, base + 8, 12, 'ACME WINES LTD\n1 HIGH STREET\nLONDON') + put(lines, base + 16, 0, acc) + put(lines, base + 16, 9, 'PO-7') + put(lines, base + 19, 0, 'B0321021\nB0308206') + put(lines, base + 19, 19, 'BAUCHET Customer Label\nDRAPPIER Carte D\'Or') + put(lines, base + 19, 55, '12\n6') + put(lines, base + 42, 89, '\xa3123.45') + lines[base + 47] = lines[base + 47][:100] + '\x0c' + return '\r\n'.join(lines) + '\r\n' + +def lpr(port, queue, control, data): + """Minimal RFC 1179 'receive a printer job' client. control is str, data is bytes.""" + s = socket.create_connection(('127.0.0.1', port), timeout=10) + def ack(): + assert s.recv(1) == b'\x00', 'no ack' + try: + s.sendall(b'\x02' + queue.encode() + b'\n'); ack() + c = control.encode('latin-1') + s.sendall(b'\x02%d cfA001testhost\n' % len(c)); ack() + s.sendall(c + b'\x00'); ack() + s.sendall(b'\x03%d dfA001testhost\n' % len(data)); ack() + s.sendall(data + b'\x00'); ack() + finally: + s.close() + +class ServerThread(threading.Thread): + def __init__(self): + threading.Thread.__init__(self) + self.daemon = True + self.running = True + def run(self): + while self.running: + asyncore.loop(timeout=0.05, count=1) + +class TestPrinterface(unittest.TestCase): + @classmethod + def setUpClass(cls): + # test discovery imports main before we get here, so repoint it (and everything derived from + # settings.HOME) at a scratch directory rather than the real ~/printerface + cls.home = tempfile.mkdtemp(prefix='printerface-test-') + main.email_pickle = os.path.join(cls.home, 'email.pickle') + main.jobdir = os.path.join(cls.home, 'data', 'pickle') + main.pdfdir = os.path.join(cls.home, 'data', 'pdf') + os.sep + main.formatter = DocFormatter(main.pdfdir) + mailer.pickle_file = os.path.join(cls.home, 'mailer.pickle') + for x in [main.jobdir, main.pdfdir]: + os.makedirs(x, exist_ok=True) + cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0) + cls.http = ToyHttpServer(ip='127.0.0.1', port=0, pathhandlers=main.path_handlers, webroot=main.web_dir) + cls.lpd_port = cls.lpd.socket.getsockname()[1] + cls.http_port = cls.http.socket.getsockname()[1] + cls.thread = ServerThread() + cls.thread.start() + + @classmethod + def tearDownClass(cls): + cls.thread.running = False + cls.thread.join() + cls.lpd.close() + cls.http.close() + shutil.rmtree(cls.home, ignore_errors=True) + + def get(self, path, headers=None): + conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) + conn.request('GET', path, headers=headers or {}) + r = conn.getresponse() + body = r.read() + conn.close() + return r, body + + def setUp(self): + main.jobs.clear() + + def send_invoice(self, **kw): + before = len(main.jobs) + lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJInvoice\nldfA001testhost\n', make_invoice(**kw).encode('latin-1')) + deadline = time.time() + 20 + while len(main.jobs) == before and time.time() < deadline: + time.sleep(0.05) + self.assertEqual(before + 1, len(main.jobs), 'job was not received') + return main.jobs[0] + + def test_lpd_to_parsed_job(self): + j = self.send_invoice() + # 8-bit data survives the transport as latin-1, and is blanked in the cleaned 'plain' text + self.assertEqual('Invoice', j['doctype']) + self.assertEqual('invoice', j['templ']) + self.assertIn('\xa3123.45', j['data']) + self.assertNotIn('\xa3', j['plain']) + self.assertEqual(['ACC001'], list(j['parsed'])) + pages = j['parsed']['ACC001'] + self.assertEqual(2, len(pages)) + # fixed row/column extraction must not be thrown off by the form feeds at the end of each page + self.assertEqual('12345', pages[0]['doc_num']) + self.assertEqual('ACC001', pages[1]['accno']) + self.assertEqual('ACME WINES LTD\n1 HIGH STREET\nLONDON\n\n\n', pages[0]['addr_invoice']) + self.assertEqual('B0321021\nB0308206', pages[0]['prod_code'].strip('\n')) + self.assertEqual('123.45', pages[0]['tot_due'].strip()) + self.assertEqual(('ACME WINES LTD',), main.email_accounts['ACC001']) + self.assertEqual({('ACC001',), ('accounts',)}, set(j['groupfiles'])) + + def test_job_pickle_is_protocol_2_and_recoverable(self): + j = self.send_invoice() + matches = [os.path.join(d, f) for d, _, fs in os.walk(main.jobdir) for f in fs if f == j['name']] + self.assertEqual(1, len(matches)) + with open(matches[0], 'rb') as f: + raw = f.read() + self.assertEqual(b'\x80\x02', raw[:2]) + name, data = j['name'], j['data'] + main.jobs.clear() + main.recover() + again = [x for x in main.jobs if x['name'] == name] + self.assertEqual(1, len(again)) + self.assertEqual(data, again[0]['data']) + self.assertEqual('12345', again[0]['parsed']['ACC001'][0]['doc_num']) + + def test_http_endpoints(self): + j = self.send_invoice() + name = j['name'] + + r, body = self.get('/recent?fmt=json') + self.assertEqual(200, r.status) + self.assertTrue(r.getheader('Content-Type').startswith('text/json')) + results = json.loads(body.decode('utf-8'))['results'] + self.assertEqual(name, results[0]['name']) + self.assertEqual('Invoice', results[0]['doctype']) + + r, body = self.get('/recent?templ=invoice') + self.assertEqual(200, r.status) + self.assertIn(name.encode(), body) + + 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'] + self.assertTrue(pdf_uri.endswith('.pdf')) + + r, body = self.get('/raw?name=' + name) + self.assertEqual(j['plain'], body.decode('utf-8')) + self.assertEqual(len(body), int(r.getheader('Content-Length'))) + # page 1 starts on row 48 and page 2 on row 96, i.e. form feeds did not add rows + rows = split_lines(j['plain']) + self.assertTrue(rows[48].startswith('INVOICE')) + self.assertTrue(rows[96].startswith('INVOICE')) + + r, body = self.get('/pdf_file?name=%s&key=ACC001' % name) + self.assertEqual(200, r.status) + self.assertEqual('application/pdf', r.getheader('Content-Type')) + self.assertEqual(b'%PDF', body[:4]) + self.assertEqual(len(body), int(r.getheader('Content-Length'))) + + r, body = self.get('/pdf_file?name=%s&key=ACC001&attach=1' % name) + self.assertIn('attachment', r.getheader('Content-Disposition')) + + for path in ['/home', '/sent', '/printers', '/settings/email', '/settings/template', + '/pdf?name=' + name, '/debug?name=' + name, '/plaintext?name=' + name, '/']: + r, body = self.get(path) + self.assertEqual(200, r.status, path) + self.assertTrue(body.strip(), path) + + r, body = self.get('/css/print.css') + self.assertEqual(200, r.status) + self.assertTrue(r.getheader('Content-Type').startswith('text/css')) + r, body = self.get('/no/such/file') + self.assertEqual(404, r.status) + + def test_email_settings_with_non_ascii_contact(self): + self.send_invoice() + r, body = self.get('/settings/email?account=ACC001&email=jose%40example.com&contact=Jos%C3%A9') + self.assertEqual(200, r.status) + self.assertIn('Jos\xe9'.encode('utf-8'), body) + self.assertEqual('Jos\xe9', main.email_addresses['ACC001']['jose@example.com']) + # saved address book reloads + main.email_addresses.clear() + main.recover() + self.assertEqual('Jos\xe9', main.email_addresses['ACC001']['jose@example.com']) + r, body = self.get('/settings/email?account=ACC001&delete=jose%40example.com') + self.assertNotIn(b'jose@example.com', body) + + def test_keepalive_two_requests_one_connection(self): + self.send_invoice() + conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) + for _ in range(2): + conn.request('GET', '/recent?fmt=json') + r = conn.getresponse() + self.assertEqual(200, r.status) + json.loads(r.read().decode('utf-8')) + conn.close() + +if __name__ == "__main__": + unittest.main() From 2f59f6ab16485a5d807ab8fc5d3b626e554cfdff Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Wed, 18 Nov 2026 16:22:18 +0000 Subject: [PATCH 04/31] Packaging for python 3.11: requirements, Dockerfile, CI, README wsgiref, MarkupSafe 0.19 and reportlab 2.7 cannot be installed on python 3. Replace Travis (python 2.7) with a GitHub Actions test workflow on 3.11. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/docker-image.yml | 2 +- .github/workflows/tests.yml | 18 ++++++++++++++++++ Dockerfile | 11 +++-------- README.md | 23 +++++++++++++++++------ requirements.txt | 10 +++++----- 5 files changed, 44 insertions(+), 20 deletions(-) create mode 100644 .github/workflows/tests.yml diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 194d077..fb06496 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -10,6 +10,6 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Build the Docker image run: docker build . --file Dockerfile --tag pritnerface:$(date +%s) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..7291780 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,18 @@ +name: Tests + +on: + push: + branches: [ master, py311 ] + pull_request: + branches: [ master ] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: pip install -r requirements.txt + - run: python -m unittest discover --pattern=*.py diff --git a/Dockerfile b/Dockerfile index a81998c..7eb9964 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,11 @@ -FROM python:2.7-alpine as builder +# asyncore/asynchat (used by lpdserver.py and httpserver.py) were removed in python 3.12 +FROM python:3.11-slim MAINTAINER chris@shucksmith.co.uk -# add the dev dependencies -RUN apk add --no-cache python make gcc g++ libc-dev - -# use cached layer for node modules COPY requirements.txt /app/ WORKDIR /app/ -RUN pip install -r requirements.txt -# RUN python -m unittest +RUN pip install --no-cache-dir -r requirements.txt RUN echo $HOME VOLUME ["/root/printerface"] @@ -21,4 +17,3 @@ COPY . /app/ WORKDIR /app RUN python -m unittest discover --pattern=*.py -# RUN ls -la /app/ diff --git a/README.md b/README.md index ca1e57c..f23b587 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # printerface -[![Build Status](https://travis-ci.org/shuckc/printerface.svg?branch=master)](https://travis-ci.org/shuckc/printerface) [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause) +[![Tests](https://github.com/shuckc/printerface/actions/workflows/tests.yml/badge.svg)](https://github.com/shuckc/printerface/actions/workflows/tests.yml) [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause) Printerface is an application that acts as a virtual printer, accepting LPD (Line Printer Daemon) documents and parses/renders them to PDF files. Documents are stored, searchable to users on your LAN using the build in web interface. Results can be browsed, emailed and automatically printed to modern network printers (anything with a CUPS/ppd driver). It has been used in production for over eight years by customers with legacy stock control/management systems, alarm pannels and fire pannels. Tea Engineering Ltd. provides commercial support and custom/integration services in the UK. @@ -29,13 +29,22 @@ The following will checkout the source code, build a docker image and start an i * `stationary.py` format JSON to nice PDF files * `printing.py` Linux printing with CUPS via. command line +Requires **python 3.11** (3.9+ for the dependencies, but `asyncore`/`asynchat` were removed from the standard library in 3.12). Requirements are specified in requirements.txt Unit tests run during `docker build` or with: - $ python -m unittest discover --pattern=*.py + $ python3.11 -m unittest discover --pattern=*.py Uses python asyncore/smtp, bootstrap web framework +Jobs, rendered PDFs, the email address book and `email.cfg` overrides live in `~/printerface`. Set the +`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`). + +Jobs and the address book are stored as pickles. They are written with pickle protocol 2 (see +`PICKLE_PROTOCOL` in `textutil.py`) so that python 2.7 can still read them, and python 2 pickles from earlier +releases are converted when loaded. Print data is treated as latin-1 throughout, one byte per column. + ### Detailed docker deploy The Dockfile fully describes how to build a containerised printerface, including dependancies. @@ -66,10 +75,12 @@ On windows you may wish to mount the job storage directory externally, as follow ### From-scratch userland python install $ mkdir ~/opt - $ wget https://www.python.org/ftp/python/2.7.18/Python-2.7.18.tgz - $ tar -xzf Python-2.7.18.tgz - $ cd Python-2.7.18 + $ wget https://www.python.org/ftp/python/3.11.10/Python-3.11.10.tgz + $ tar -xzf Python-3.11.10.tgz + $ cd Python-3.11.10 $ ./configure prefix=$HOME/opt --with-ensurepip=install $ make && make install - $ ~/opt/bin/pip install -r ~/repos/printerface/requirements.txt + $ ~/opt/bin/python3.11 -m pip install -r ~/repos/printerface/requirements.txt +On older distributions pip has no prebuilt wheels for `pillow`, so you also need a compiler and the +`libjpeg` and `zlib` development headers installed to build it. diff --git a/requirements.txt b/requirements.txt index 47d9e33..ce372f6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ -Mako==1.2.2 -MarkupSafe==0.19 -reportlab==2.7 -wsgiref==0.1.2 -pytz==2018.9 +Mako>=1.2.2 +MarkupSafe>=2.0 +reportlab>=4.0,<6 +pillow>=9.0 +pytz>=2023.3 From a03b7e006270acf276960cd84b695fb626799e61 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 09:14:28 +0000 Subject: [PATCH 05/31] Add corpus comparison and LPD replay tools compare_corpus.py re-renders stored jobs and diffs PDF text against the PDFs made by the previous release; replay_corpus.py sends stored payloads through the LPD server as a real client would, including the Windows end-of-file-by-close variant. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 4 ++ tools/compare_corpus.py | 87 +++++++++++++++++++++++++++++++++++++++ tools/replay_corpus.py | 91 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 182 insertions(+) create mode 100755 tools/compare_corpus.py create mode 100755 tools/replay_corpus.py diff --git a/README.md b/README.md index f23b587..4bd0928 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,10 @@ 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`). +`tools/compare_corpus.py` and `tools/replay_corpus.py` check a port or upgrade against real data: given a copy of +`data/pickle` and `data/pdf` from a running system, the first re-renders every job and compares the PDF text +with the PDFs the previous release produced, the second replays every stored payload through the LPD server. + Jobs and the address book are stored as pickles. They are written with pickle protocol 2 (see `PICKLE_PROTOCOL` in `textutil.py`) so that python 2.7 can still read them, and python 2 pickles from earlier releases are converted when loaded. Print data is treated as latin-1 throughout, one byte per column. diff --git a/tools/compare_corpus.py b/tools/compare_corpus.py new file mode 100755 index 0000000..2c249f8 --- /dev/null +++ b/tools/compare_corpus.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3.11 +"""Characterisation check of the python 3 code against output produced by the python 2 release. + + tools/compare_corpus.py CORPUS OUTDIR [--since YYYYMMDD] + +CORPUS is a directory laid out like ~/printerface (data/pickle/YYYYMM/job-*, data/pdf/...), copied from a +system running the python 2 release. Every job is loaded and run through main.cleanJob, which parses it and +renders PDFs into OUTDIR (never into ~/printerface). Each rendered PDF is then compared, as text extracted +by pdftotext, against the PDF python 2 made for the same job in CORPUS. +""" +import argparse +import collections +import contextlib +import io +import os +import subprocess +import sys +import traceback + +ap = argparse.ArgumentParser() +ap.add_argument('corpus') +ap.add_argument('outdir') +ap.add_argument('--since', default='') +ap.add_argument('--show', type=int, default=5, help='how many differences to print per category') +args = ap.parse_args() + +corpus = os.path.abspath(args.corpus) +os.environ['PRINTERFACE_HOME'] = os.path.abspath(args.outdir) +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import main +from textutil import load_job_pickle + +def pdftext(path): + out = subprocess.run(['pdftotext', '-layout', path, '-'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout + return [l.rstrip() for l in out.decode('utf-8', 'replace').split('\n')] + +pickle_root = os.path.join(corpus, 'data', 'pickle') +errors, noref, same, differ = [], [], [], [] +by_templ = collections.Counter() +by_doctype = collections.Counter() +non_ascii_plain = 0 +jobs = 0 + +for yyyymm in sorted(os.listdir(pickle_root)): + for name in sorted(os.listdir(os.path.join(pickle_root, yyyymm))): + if not name.startswith('job-') or name[4:] < args.since: + continue + jobs += 1 + try: + with open(os.path.join(pickle_root, yyyymm, name), 'rb') as f: + j = load_job_pickle(f) + j['name'] = name + with contextlib.redirect_stdout(io.StringIO()): + main.cleanJob(j) + except Exception: + errors.append((name, traceback.format_exc().strip().split('\n')[-1])) + continue + by_templ[j['templ']] += 1 + by_doctype[j['doctype']] += 1 + if not j['plain'].isascii(): + non_ascii_plain += 1 + for key, rel in sorted(j['groupfiles'].items()): + ref = os.path.join(corpus, 'data', 'pdf', rel) + new = os.path.join(main.pdfdir, rel) + if not os.path.exists(ref): + noref.append((name, rel)) + continue + a, b = pdftext(ref), pdftext(new) + if a == b: + same.append((name, rel)) + else: + n = next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b))) + differ.append((name, rel, n, a[n:n + 1], b[n:n + 1], len(a), len(b))) + +print('jobs=%d load/parse errors=%d non-ascii plain text=%d' % (jobs, len(errors), non_ascii_plain)) +print('by templ :', dict(by_templ)) +print('by doctype :', dict(by_doctype)) +print('pdfs: identical text=%d different=%d no reference pdf=%d' % (len(same), len(differ), len(noref))) +for e in errors[:args.show]: + print('ERROR', e) +for d in differ[:args.show]: + print('DIFF %s %s line %d\n py2: %r\n py3: %r (lines %d vs %d)' % d) +for n in noref[:args.show]: + print('NOREF', n) +sys.exit(1 if errors or differ else 0) diff --git a/tools/replay_corpus.py b/tools/replay_corpus.py new file mode 100755 index 0000000..fa266cd --- /dev/null +++ b/tools/replay_corpus.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3.11 +"""Replay stored print jobs through the LPD server as a real RFC 1179 client would send them and check that +the payload and control file arrive unchanged. + + tools/replay_corpus.py CORPUS [--since job-YYYYMMDD] + +CORPUS is laid out like ~/printerface (data/pickle/YYYYMM/job-*). Nothing is written to disk; the server +side is a recording callback rather than main.saveJob. +""" +import argparse +import asyncore +import os +import sys +import threading + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from lpdserver import LpdServer +from textutil import load_job_pickle + +ap = argparse.ArgumentParser() +ap.add_argument('corpus') +ap.add_argument('--since', default='job-') +args = ap.parse_args() + +received = [] +server = LpdServer(lambda queue, local, remote, control, data: received.append((queue, control, data)), ip='127.0.0.1', port=0) +port = server.socket.getsockname()[1] +running = True +def loop(): + while running: + asyncore.loop(timeout=0.02, count=1) +threading.Thread(target=loop, daemon=True).start() + +import socket +def send(queue, control, data, eof_by_close=False): + s = socket.create_connection(('127.0.0.1', port), timeout=10) + def ack(): + assert s.recv(1) == b'\x00', 'no ack' + try: + s.sendall(b'\x02' + queue.encode('latin-1') + b'\n'); ack() + c = control.encode('latin-1') + s.sendall(b'\x02%d cfA001host\n' % len(c)); ack() + s.sendall(c + b'\x00'); ack() + if eof_by_close: + # windows lpr declares a stupidly large size and signals the end of the file by closing the socket + s.sendall(b'\x03%d dfA001host\n' % 0x7fffffff); ack() + s.sendall(data) + s.shutdown(socket.SHUT_WR) + s.recv(1) + else: + s.sendall(b'\x03%d dfA001host\n' % len(data)); ack() + s.sendall(data + b'\x00'); ack() + finally: + s.close() + +root = os.path.join(args.corpus, 'data', 'pickle') +sent = bad = 0 +nul_terminated = 0 +sizes = 0 +for yyyymm in sorted(os.listdir(root)): + for name in sorted(os.listdir(os.path.join(root, yyyymm))): + if not name.startswith('job-') or name < args.since: + continue + with open(os.path.join(root, yyyymm, name), 'rb') as f: + j = load_job_pickle(f) + # the stored payload still carries the protocol's trailing NUL, which the server adds back + data = j['data'] + by_close = not data.endswith('\x00') + if not by_close: + nul_terminated += 1 + data = data[:-1] + raw = data.encode('latin-1') + control = ''.join('%s%s\n' % kv for kv in j['control'].items()) + before = len(received) + send(j.get('queue', 'RAW'), control, raw, eof_by_close=by_close) + for _ in range(500): + if len(received) > before: + break + threading.Event().wait(0.01) + sent += 1 + sizes += len(raw) + if len(received) == before: + bad += 1; print('NOT RECEIVED', name) + continue + queue, rcontrol, rdata = received[-1] + if rdata != j['data'] or rcontrol != j['control'] or queue != j.get('queue', 'RAW'): + bad += 1; print('MISMATCH', name, len(rdata), len(j['data']), rcontrol == j['control']) + +running = False +print('replayed=%d (%.1f MiB): sized transfers=%d, eof-by-close transfers=%d, mismatches=%d' % (sent, sizes / 1048576.0, nul_terminated, sent - nul_terminated, bad)) +sys.exit(1 if bad else 0) From 11e1681b6abe636a709dd7eb26a5890279cc0add Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 09:23:00 +0000 Subject: [PATCH 06/31] Add compare_http.py: diff the read-only API of two instances Compares /recent, /job and /raw over the jobs both instances hold, ignoring the unreliable 'ts' field and JSON key order (python 2 dict order was arbitrary). Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 ++ tools/compare_http.py | 71 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100755 tools/compare_http.py diff --git a/README.md b/README.md index 4bd0928..af59cec 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,8 @@ against a copy of the data on other ports (`lpd_port` and `http_port` in `defaul `tools/compare_corpus.py` and `tools/replay_corpus.py` check a port or upgrade against real data: given a copy of `data/pickle` and `data/pdf` from a running system, the first re-renders every job and compares the PDF text with the PDFs the previous release produced, the second replays every stored payload through the LPD server. +`tools/compare_http.py` compares the read-only `/recent`, `/job` and `/raw` API of two running instances over the +jobs they both hold, for checking a candidate against the live release. Jobs and the address book are stored as pickles. They are written with pickle protocol 2 (see `PICKLE_PROTOCOL` in `textutil.py`) so that python 2.7 can still read them, and python 2 pickles from earlier diff --git a/tools/compare_http.py b/tools/compare_http.py new file mode 100755 index 0000000..8a52f14 --- /dev/null +++ b/tools/compare_http.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3.11 +"""Compare the read-only HTTP API of two printerface instances (for example the python 2 release and a +python 3 candidate) over the jobs they both hold. Only GET /recent, /job and /raw are used. + + tools/compare_http.py http://localhost:8081 http://localhost:18081 [--limit 100] [--delay 0.15] + +The instances may hold different windows of jobs, so only jobs present in both are compared. Not compared: +the 'ts' field of /recent (it reports one job's timestamp for every row) and the order of keys inside JSON +objects (python 2 dicts had arbitrary order). Order of jobs, of accounts inside 'parsed' and the values of +every field are compared. Exit status is non-zero on any difference. +""" +import argparse +import json +import sys +import time +import urllib.request + +ap = argparse.ArgumentParser() +ap.add_argument('ref') +ap.add_argument('cand') +ap.add_argument('--limit', type=int, default=100, help='max parsed documents to compare with /job') +ap.add_argument('--raw', type=int, default=5, help='max stock-report jobs to compare with /raw') +ap.add_argument('--delay', type=float, default=0.15, help='seconds between requests (the server is a single event loop)') +args = ap.parse_args() + +def get(base, path): + time.sleep(args.delay) + with urllib.request.urlopen(base.rstrip('/') + path, timeout=120) as r: + return r.read() + +def recent_all(base): + out, page = [], 0 + while True: + d = json.loads(get(base, '/recent?query=&templ=&doctype=&page=%d&fmt=json' % page).decode('utf-8')) + out += d['results'] + if not d['next']: + return out + page += 1 + +ref, cand = recent_all(args.ref), recent_all(args.cand) +R, C = {r['name']: r for r in ref}, {r['name']: r for r in cand} +common = [r['name'] for r in ref if r['name'] in C] +fails = 0 +def fail(*a): + global fails + fails += 1 + print('DIFF', *a) + +print('/recent: ref=%d cand=%d common=%d' % (len(ref), len(cand), len(common))) +for n in common: + for k in ('host', 'doctype', 'details'): + if R[n][k] != C[n][k]: + fail('/recent', n, k, R[n][k], C[n][k]) +if common != [r['name'] for r in cand if r['name'] in R]: + fail('/recent order of common jobs differs') + +parsed = [n for n in common if R[n]['details']][:args.limit] +for n in parsed: + a = json.loads(get(args.ref, '/job?name=' + n).decode('utf-8')) + b = json.loads(get(args.cand, '/job?name=' + n).decode('utf-8')) + if a != b: + fail('/job', n, [k for k in a if a[k] != b.get(k)]) +print('/job: compared %d parsed documents' % len(parsed)) + +stock = [n for n in common if R[n]['doctype'] in ('D.PR6', 'D.AEB28A', 'D.SIZE')][:args.raw] +for n in stock: + if get(args.ref, '/raw?name=' + n) != get(args.cand, '/raw?name=' + n): + fail('/raw', n) +print('/raw: compared %d stock report jobs' % len(stock)) +print('FAILED: %d differences' % fails if fails else 'OK: no differences') +sys.exit(1 if fails else 0) From df8892015c258320e2a9dce3cb52a46479711199 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 10:26:45 +0000 Subject: [PATCH 07/31] init.d: run main.py with an explicit python 3.11 interpreter The script relied on main.py's shebang and a PATH that found the python 2.7 build first. Default to ~/.venv311/bin/python (a venv of /opt/python311/bin/python3.11), overridable with PRINTERFACE_PYTHON, and refuse to start if it is missing. Co-Authored-By: Claude Sonnet 5.5 --- init.d/printerface | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/init.d/printerface b/init.d/printerface index 0b3b098..b631965 100755 --- a/init.d/printerface +++ b/init.d/printerface @@ -29,6 +29,11 @@ # Location of printerface binary printerface=~/repos/printerface/main.py +# Interpreter to run it with. Needs python 3.11 (asyncore was removed in 3.12) plus the packages from +# requirements.txt, so default to a venv made from /opt/python311/bin/python3.11: +# /opt/python311/bin/python3.11 -m venv ~/.venv311 && ~/.venv311/bin/pip install -r requirements.txt +# Set PRINTERFACE_PYTHON to use another one. +python=${PRINTERFACE_PYTHON:-~/.venv311/bin/python} lock=~/printerface/lock pidfile=~/printerface/run work=~/repos/printerface/ @@ -47,12 +52,19 @@ then fi # Check that binary exists -if ! [ -f $printerface ] +if ! [ -f $printerface ] then echo "printerface binary not found" exit 0 fi +# Check that the interpreter exists +if ! [ -x $python ] +then + echo "python interpreter $python not found" + exit 0 +fi + # See how we were called. case "$1" in start) @@ -77,7 +89,7 @@ case "$1" in errors=0 successes=0 export TZ=:/etc/localtime - daemonize -a -E PATH=$PATH -c $work -e $logfile.err -o $logfile.out -p $pidfile $printerface + daemonize -a -E PATH=$PATH -c $work -e $logfile.err -o $logfile.out -p $pidfile $python $printerface if [ $? = 0 ]; then successes=1 From 7ad28b8fb3ccc10c1e24f908e234128156dbff12 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 10:39:42 +0000 Subject: [PATCH 08/31] Fix /plaintext: loop over a list, mako's loop.last needs len() filter() is lazy on python 3 so the page rendered a mako error (as a 200). The integration test fetched the page but only checked for a non-empty body; it now fails on mako error pages and checks one
     per printed page.
    
    Co-Authored-By: Claude Sonnet 5.5 
    ---
     test_integration.py | 8 ++++++++
     web/plain.html      | 2 +-
     2 files changed, 9 insertions(+), 1 deletion(-)
    
    diff --git a/test_integration.py b/test_integration.py
    index fd35d33..e32142e 100644
    --- a/test_integration.py
    +++ b/test_integration.py
    @@ -193,6 +193,14 @@ def test_http_endpoints(self):
     			r, body = self.get(path)
     			self.assertEqual(200, r.status, path)
     			self.assertTrue(body.strip(), path)
    +			# mako (format_exceptions=True) renders a template failure as a normal 200 page
    +			self.assertNotIn(b'Mako Runtime Error', body, path)
    +			self.assertNotIn(b'Traceback', body, path)
    +
    +		# one 
     per printed page: the two invoice pages are separated by form feeds
    +		r, body = self.get('/plaintext?name=' + name)
    +		self.assertEqual(2, body.count(b'
    Plain Text
     		 Document Pages		
     	% endif
     		
    -	% for part in filter(None, job['plain'].strip().split("\f")):
    +	% for part in [p for p in job['plain'].strip().split("\f") if p]:
     	% if loop.last:
     	
    ${part.rstrip() | h}
    % else: From a78c98b0071ee7d545a70d206dd4009a12b36e23 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 10:47:54 +0000 Subject: [PATCH 09/31] Bump template copyright footer to 2026 Co-Authored-By: Claude Sonnet 5.5 --- web/bootstrap.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/bootstrap.html b/web/bootstrap.html index 4156b88..f4ead61 100644 --- a/web/bootstrap.html +++ b/web/bootstrap.html @@ -64,7 +64,7 @@
    -

    © Tea Engineering Ltd 2013-2019

    +

    © Tea Engineering Ltd 2013-2026

    From a00297d5066ccfb63c317f8dac14a4ee810acc0b Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 11:34:02 +0000 Subject: [PATCH 10/31] Fix /recent json: report each job's own ts The row used j['ts'], the loop variable leaked from the filter loop above, so every result carried the same timestamp. Use p['ts']. Adds a test that two jobs get their own timestamps. Co-Authored-By: Claude Sonnet 5.5 --- main.py | 2 +- test_integration.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index e649410..be22557 100755 --- a/main.py +++ b/main.py @@ -232,7 +232,7 @@ def recent(query_string=dict(), resp=None): if fmt == 'json': nextQry = base_uri + '/recent?query={query}&templ={templ}&doctype={doctype}&page={page}&fmt={fmt}'.format(query=query, templ=templ, doctype=doctype, page=page+1, fmt=fmt) output = { 'results': [ - { 'name': p['name'], 'host': p['control'].get('H'), 'doctype': p['doctype'], 'ts': j['ts'].isoformat(), 'details': + { 'name': p['name'], 'host': p['control'].get('H'), 'doctype': p['doctype'], 'ts': p['ts'].isoformat(), 'details': ('' if not p['templ'] else '{base}/job?name={name}'.format(base=base_uri, name=p['name'])) } for p in pagejobs[page] ], 'next': '' if page >= len(pagejobs)-1 else nextQry } diff --git a/test_integration.py b/test_integration.py index e32142e..af5fb01 100644 --- a/test_integration.py +++ b/test_integration.py @@ -221,6 +221,16 @@ def test_email_settings_with_non_ascii_contact(self): r, body = self.get('/settings/email?account=ACC001&delete=jose%40example.com') self.assertNotIn(b'jose@example.com', body) + def test_recent_json_ts_is_per_job(self): + first = self.send_invoice(doc_num='111') + second = self.send_invoice(doc_num='222') + self.assertNotEqual(first['ts'], second['ts']) + r, body = self.get('/recent?fmt=json') + rows = {x['name']: x for x in json.loads(body.decode('utf-8'))['results']} + # ts is the job's own (naive, utc) receive time; it used to be the oldest loaded job's for every row + self.assertEqual(first['ts'].isoformat(), rows[first['name']]['ts']) + self.assertEqual(second['ts'].isoformat(), rows[second['name']]['ts']) + def test_keepalive_two_requests_one_connection(self): self.send_invoice() conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) From 98dbbb39c8fd9e0fa268a77670819d7421293090 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:07:55 +0000 Subject: [PATCH 11/31] Per document type email templates, with a web editor and preview The email text offered for an invoice, purchase order or statement now comes from a Mako template (~/printerface/templates/.mako, falling back to the copy in templates/ in the source) that can use the document's fields, the recipients' names and the company details. Settings > Email Templates edits them with a preview against a real document, chosen by document number or account. Mako can run python and the web interface has no authentication, so the editor only accepts a safe subset (field lookups, for/if over documents, comments) and refuses anything else, including in previews. Other document types keep the single default text. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 19 ++ emailtemplates.py | 411 ++++++++++++++++++++++++++++++++++++ main.py | 72 ++++++- templates/invoice.mako | 9 + templates/purchase.mako | 10 + templates/statement.mako | 10 + test_integration.py | 112 ++++++++++ web/bootstrap.html | 3 +- web/pdf.html | 8 +- web/settings_template.html | 3 +- web/settings_templates.html | 99 +++++++++ 11 files changed, 751 insertions(+), 5 deletions(-) create mode 100644 emailtemplates.py create mode 100644 templates/invoice.mako create mode 100644 templates/purchase.mako create mode 100644 templates/statement.mako create mode 100644 web/settings_templates.html diff --git a/README.md b/README.md index af59cec..7d789ba 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,25 @@ 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`). +### Email templates + +The text offered when emailing a document comes from a template per document type: `invoice`, `purchase` and +`statement` (other types use the single "Default Email Text" under Settings). Templates are Mako files. +`~/printerface/templates/.mako` is used if it exists, otherwise the copy shipped in `templates/` in the +source, so an install that never customises a template follows the repository. Edit them under +Settings > Email Templates, which previews the result against a real document (leave the filter blank for the +newest, or enter a document number or account). + +Variables: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`, +`doc.customer`, ... - the editor lists them), `${email.name}`, `${email.address}`, `${job.name}`, +`${company.name}`. If an account has several documents in one print run `doc` is the last; use +`% for d in docs:` ... `% endfor` to visit each. `% if doc.field:` / `% else:` / `% endif` and `##` comments work too. + +The web interface has no authentication and Mako can run arbitrary python, so the editor only accepts that +subset (no calls, operators, `<% %>` blocks or names starting with an underscore; see `emailtemplates.validate`). +Files placed in `~/printerface/templates` by hand are trusted, but one that no longer renders falls back to the +shipped template with a warning. + `tools/compare_corpus.py` and `tools/replay_corpus.py` check a port or upgrade against real data: given a copy of `data/pickle` and `data/pdf` from a running system, the first re-renders every job and compares the PDF text with the PDFs the previous release produced, the second replays every stored payload through the LPD server. diff --git a/emailtemplates.py b/emailtemplates.py new file mode 100644 index 0000000..d61fb87 --- /dev/null +++ b/emailtemplates.py @@ -0,0 +1,411 @@ +# Email body templates, one per document type. +# +# The text offered when emailing a document is rendered from a Mako template chosen by the type of the +# job (invoice, purchase order, statement). Templates are looked up in USER_DIR (~/printerface/templates) +# first and fall back to the copies shipped with the source in SEED_DIR, so an install that has never +# customised a template keeps following the repository. The web editor saves into USER_DIR. +# +# SECURITY: Mako can run arbitrary python and the web interface has no authentication. Anything that +# comes from the editor (previews included) is therefore checked by validate() first, which only allows +# plain text, ${field.lookups}, 'for ... in docs', simple 'if' tests and comments. There are no calls, no +# <% %> blocks, no operators and no names starting with an underscore, so a template cannot reach +# anything but the document data it is given. +import collections +import os +import re +import unittest + +from mako.template import Template + +from settings import BASE_DIR, HOME + +KINDS = collections.OrderedDict([('invoice', 'Invoice'), ('purchase', 'Purchase order'), ('statement', 'Statement')]) +# job['templ'] -> template kind. Other document types (credit notes, delivery notes...) have no template of +# their own and keep using the single default email text. +KIND_FOR_TEMPL = {'invoice': 'invoice', 'purchase': 'purchase', 'statement': 'statement'} + +SEED_DIR = os.path.join(BASE_DIR, 'templates') +USER_DIR = os.path.join(HOME, 'templates') + +ENCODING = 'utf-8' +NO_NAME = 'Sir or Madam' + +class TemplateError(Exception): + def __init__(self, errors): + Exception.__init__(self, '; '.join(errors)) + self.errors = errors + +# ---------------------------------------------------------------------------------------------- context + +class Fields(object): + """Read-only attribute access to a dict of values. A field that does not exist reads as '' so that a + template written for one document layout never fails on another.""" + def __init__(self, values): + self.__dict__.update(values) + + def __getattr__(self, name): + if name.startswith('_'): + raise AttributeError(name) + return '' + +def field_names(fields): + return sorted(k for k in vars(fields)) + +def merge_documents(pages): + """Pages of one account in a job -> one dict per document (grouped by document number, in print order). + A document's totals are only printed on its last page, so a later non-empty value replaces an earlier + one. Statements have no document number: all their pages are one document.""" + docs = collections.OrderedDict() + for page in pages: + d = docs.setdefault(page.get('doc_num', '').strip(), {}) + for k, v in page.items(): + v = v.strip() if isinstance(v, str) else v + if v or k not in d: + d[k] = v + for d in docs.values(): + d['customer'] = d.get('addr_invoice', '').split('\n')[0].strip() + return list(docs.values()) + +def account_for_key(parsed, key): + """PDF group key -> account code. Purchase orders also have '-admin' and '-transport'.""" + if key in parsed: + return key + for suffix in ('-admin', '-transport'): + if key.endswith(suffix) and key[:-len(suffix)] in parsed: + return key[:-len(suffix)] + return None + +def join_names(names): + names = [n.strip() for n in dict.fromkeys(names) if n and n.strip()] + if not names: + return NO_NAME + if len(names) == 1: + return names[0] + return ', '.join(names[:-1]) + ' and ' + names[-1] + +def kind_for_job(job): + return KIND_FOR_TEMPL.get(job.get('templ')) + +def build_context(job, key, names=(), addresses=(), company=None): + """The variables a template sees: + doc the document (the last one, if the account has several in this print run); doc. + docs every document for the account in this print run, for '% for d in docs:' + 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""" + parsed = job.get('parsed') or {} + acc = account_for_key(parsed, key) + docs = merge_documents(parsed[acc]) if acc else [] + addresses = [a for a in addresses if a] + return dict( + doc=Fields(docs[-1] if docs else {}), + docs=[Fields(d) for d in docs], + email=Fields({'name': join_names(names), 'address': addresses[0] if addresses else ''}), + job=Fields({'name': job.get('name', ''), 'doctype': job.get('doctype', ''), 'host': (job.get('control') or {}).get('H', '')}), + company=Fields(company or {})) + +def find_document(jobs, kind, term=''): + """The filter behind the editor's preview. jobs is newest first. Returns (job, account) for the newest + document of this kind whose document number, or account code, equals term (ignoring case and spaces), + or for the newest document of this kind if term is empty. None if there isn't one.""" + norm = lambda s: re.sub(r'\s+', '', s or '').lower() + want = norm(term) + for job in jobs: + if kind_for_job(job) != kind: + continue + for acc, pages in (job.get('parsed') or {}).items(): + for d in merge_documents(pages): + if not want or want in (norm(d.get('doc_num')), norm(d.get('accno'))): + return job, acc + return None + +# ------------------------------------------------------------------------------------------ validation + +# a name may contain, but not start with, an underscore: field names are like tot_due, and this keeps __dunder__ out +_PATH = r'[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*' +_EXPR = re.compile(r'^\s*(%s)\s*(?:\|\s*trim\s*)?$' % _PATH) +_FOR = re.compile(r'^\s*%\s*for\s+([a-z][a-z0-9]*)\s+in\s+docs\s*:\s*$') +_IF = re.compile(r'^\s*%%\s*if\s+(?:not\s+)?(%s)\s*:\s*$' % _PATH) +_ELSE = re.compile(r'^\s*%\s*else\s*:\s*$') +_END = re.compile(r'^\s*%\s*(?:endif|endfor)\s*$') +_ROOTS = frozenset(['doc', 'email', 'job', 'company']) + +def validate(text): + """Returns a list of 'line N: problem' strings; empty if the template is safe to render.""" + errors = [] + loop_vars = set() + lines = text.replace('\r\n', '\n').replace('\r', '\n').split('\n') + for line in lines: + m = _FOR.match(line) + if m: + loop_vars.add(m.group(1)) + roots = _ROOTS | loop_vars + + def check_path(n, path, where): + root = path.split('.')[0] + if root not in roots: + errors.append('line %d: unknown name "%s" in %s (use %s)' % (n, root, where, ', '.join(sorted(roots)))) + + for n, line in enumerate(lines, 1): + if line.endswith('\\'): + errors.append('line %d: a line may not end with a backslash' % n) + if '<%' in line or ' blocks are not allowed' % n) + continue + stripped = line.lstrip() + if stripped.startswith('##'): + continue + if stripped.startswith('%'): + m = _IF.match(line) + if m: + check_path(n, m.group(1), 'the condition') + elif not (_FOR.match(line) or _ELSE.match(line) or _END.match(line)): + errors.append('line %d: only "%% for x in docs:", "%% if field:", "%% if not field:", "%% else:", "%% endif" and "%% endfor" are allowed' % n) + continue + found = 0 + for em in re.finditer(r'\$\{(.*?)\}', line): + found += 1 + m = _EXPR.match(em.group(1)) + if not m: + errors.append('line %d: "${%s}" is not allowed; use ${doc.field} or ${doc.field | trim}' % (n, em.group(1).strip())) + else: + check_path(n, m.group(1), '${%s}' % em.group(1).strip()) + if line.count('${') != found: + errors.append('line %d: unterminated ${' % n) + if not errors: + try: + Template(text) + except Exception as e: + errors.append('template structure: %s' % (str(e).splitlines() or ['invalid'])[0]) + return errors + +def render(text, context): + errors = validate(text) + if errors: + raise TemplateError(errors) + try: + out = Template(text, strict_undefined=True).render_unicode(**context) + except Exception as e: + raise TemplateError(['%s: %s' % (type(e).__name__, e)]) + return out.rstrip() + '\n' + +# ------------------------------------------------------------------------------------------ storage + +def _check_kind(kind): + if kind not in KINDS: + raise KeyError('unknown template %r' % (kind,)) + +def user_path(kind): + _check_kind(kind) + return os.path.join(USER_DIR, kind + '.mako') + +def seed_path(kind): + _check_kind(kind) + return os.path.join(SEED_DIR, kind + '.mako') + +def load(kind): + """(text, 'custom' | 'default'): the user's template if they have one, else the one shipped in the source.""" + for source, path in (('custom', user_path(kind)), ('default', seed_path(kind))): + if os.path.isfile(path): + with open(path, encoding=ENCODING) as f: + return f.read(), source + raise FileNotFoundError(seed_path(kind)) + +def save(kind, text): + text = text.replace('\r\n', '\n').replace('\r', '\n') + if not text.endswith('\n'): + text += '\n' + errors = validate(text) + if errors: + raise TemplateError(errors) + path = user_path(kind) + os.makedirs(USER_DIR, exist_ok=True) + tmp = path + '.tmp' + with open(tmp, 'w', encoding=ENCODING, newline='\n') as f: + f.write(text) + os.replace(tmp, path) + +def revert(kind): + """Delete the user's copy so the shipped template applies again. True if there was one.""" + path = user_path(kind) + if os.path.isfile(path): + os.remove(path) + return True + return False + +def render_for_job(job, key, names=(), addresses=(), company=None): + """(body, kind, warning) for the compose form, or (None, None, None) for a document type without its + own template. A user template that no longer renders falls back to the shipped one, with a warning.""" + kind = kind_for_job(job) + if not kind: + return None, None, None + context = build_context(job, key, names, addresses, company) + text, source = load(kind) + try: + return render(text, context), kind, None + except TemplateError as e: + if source != 'custom': + raise + body = render(open(seed_path(kind), encoding=ENCODING).read(), context) + return body, kind, 'Your %s template could not be used (%s); showing the default.' % (KINDS[kind].lower(), e) + +# ----------------------------------------------------------------------------------------------- tests + +class TestEmailTemplates(unittest.TestCase): + def pages(self): + return [ + {'doc_num': '336769', 'ourref': '289073', 'accno': 'HAR108', 'tot_due': '', 'addr_invoice': 'HISTORIC HOUSE\nAYLESBURY\n\n', 'page': '1'}, + {'doc_num': '336769', 'ourref': '289073', 'accno': 'HAR108', 'tot_due': '1,234.50', 'addr_invoice': 'HISTORIC HOUSE\nAYLESBURY\n\n', 'page': '2'}, + {'doc_num': '336770', 'ourref': '289099', 'accno': 'HAR108', 'tot_due': '10.00', 'addr_invoice': 'HISTORIC HOUSE\n', 'page': '1'}, + ] + + def job(self, templ='invoice', name='job-1'): + return {'name': name, 'templ': templ, 'doctype': 'Invoice', 'control': {'H': 'SALES-PC'}, 'parsed': {'HAR108': self.pages()}} + + def test_merge_documents_takes_totals_from_the_last_page(self): + docs = merge_documents(self.pages()) + self.assertEqual(['336769', '336770'], [d['doc_num'] for d in docs]) + self.assertEqual('1,234.50', docs[0]['tot_due']) + self.assertEqual('HISTORIC HOUSE', docs[0]['customer']) + self.assertEqual('2', docs[0]['page']) + + def test_statement_pages_without_doc_num_are_one_document(self): + docs = merge_documents([{'accno': 'A', 'tot_topay': ''}, {'accno': 'A', 'tot_topay': '5.00'}]) + self.assertEqual(1, len(docs)) + self.assertEqual('5.00', docs[0]['tot_topay']) + + def test_account_for_key(self): + parsed = {'APA100': [], 'MULTI-21': []} + self.assertEqual('APA100', account_for_key(parsed, 'APA100')) + self.assertEqual('APA100', account_for_key(parsed, 'APA100-admin')) + self.assertEqual('APA100', account_for_key(parsed, 'APA100-transport')) + self.assertEqual('MULTI-21', account_for_key(parsed, 'MULTI-21')) + self.assertIsNone(account_for_key(parsed, 'accounts')) + + def test_join_names(self): + self.assertEqual(NO_NAME, join_names([])) + self.assertEqual('Ann', join_names(['Ann', 'Ann', ' '])) + self.assertEqual('Ann and Bob', join_names(['Ann', 'Bob'])) + self.assertEqual('Ann, Bob and Cy', join_names(['Ann', 'Bob', 'Cy'])) + + def test_shipped_templates_are_valid_and_the_invoice_text_is_as_specified(self): + for kind in KINDS: + text = open(seed_path(kind), encoding=ENCODING).read() + self.assertEqual([], validate(text), kind) + ctx = build_context(self.job(), 'HAR108', names=['Ann']) + body = render(open(seed_path('invoice'), encoding=ENCODING).read(), ctx) + self.assertEqual('To Ann\n\nPlease find your latest invoice 289099 attached for account HAR108, for \xa310.00.\n', body) + + def test_shipped_templates_render_with_no_data_at_all(self): + for kind in KINDS: + body = render(open(seed_path(kind), encoding=ENCODING).read(), build_context({}, 'nothing')) + self.assertTrue(body.startswith('To ' + NO_NAME), kind) + + def test_other_document_types_have_no_template(self): + self.assertIsNone(render_for_job({'templ': 'delnote'}, 'X')[0]) + self.assertIsNone(render_for_job({'templ': None}, 'X')[0]) + + def test_validate_accepts_the_safe_subset(self): + ok = '''## a comment ${anything()} +To ${email.name | trim} +% for d in docs: +Invoice ${d.ourref}: ${d.tot_due} +% endfor +% if doc.tot_due: +Total ${doc.tot_due} +% else: +none +% endif +% if not doc.customer: +x +% endif +50% off, 100% sure +''' + self.assertEqual([], validate(ok)) + + def test_validate_rejects_anything_that_could_run_code(self): + bad = [ + "${__import__('os').system('id')}", + '${doc.__class__}', + '${doc.ourref()}', + '${doc.ourref + doc.accno}', + '${open("/etc/passwd").read()}', + '${os.getcwd}', + '${doc.ourref | h}', + '${doc.ourref', + '<% import os %>', + '<%! import os %>', + '<%include file="x"/>', + '% import os', + '% for x in range(3):\n% endfor', + '% if doc.a == 1:\n% endif', + '% if doc.a:\n% endif\n%% x', + '${doc.ourref}\\\n% import os', + '% for x in docs:\n${y.ourref}\n% endfor', + ] + for text in bad: + self.assertTrue(validate(text), text) + with self.assertRaises(TemplateError): + render("${__import__('os').system('true')}", build_context({}, 'x')) + + def test_comments_are_never_evaluated(self): + # validate() skips '##' lines, so make sure mako really does too (strict_undefined would raise) + self.assertEqual('hello\n', render('## ${nothing.defined.here}\nhello', build_context({}, 'x'))) + # ...but <% is refused everywhere, comment or not + self.assertTrue(validate('## <% x %>')) + + def test_validate_reports_unbalanced_blocks(self): + self.assertTrue(validate('% if doc.a:\nx\n')) + + def test_storage_custom_overrides_shipped_and_revert_restores(self): + import tempfile + global USER_DIR + old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates') + try: + text, source = load('invoice') + self.assertEqual('default', source) + save('invoice', 'Hello ${email.name}\r\nbye') + text, source = load('invoice') + self.assertEqual(('Hello ${email.name}\nbye\n', 'custom'), (text, source)) + with self.assertRaises(TemplateError): + save('invoice', '${__import__("os")}') + self.assertEqual('Hello ${email.name}\nbye\n', load('invoice')[0]) + self.assertTrue(revert('invoice')) + self.assertFalse(revert('invoice')) + self.assertEqual('default', load('invoice')[1]) + with self.assertRaises(KeyError): + user_path('../../etc/passwd') + finally: + import shutil + shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True) + USER_DIR = old + + def test_a_broken_custom_template_falls_back_to_the_shipped_one(self): + import tempfile + global USER_DIR + old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates') + try: + os.makedirs(USER_DIR) + with open(user_path('invoice'), 'w') as f: + f.write('${__import__("os")}') # written to disk behind the editor's back + body, kind, warning = render_for_job(self.job(), 'HAR108', ['Ann']) + self.assertTrue(body.startswith('To Ann\n\nPlease find your latest invoice')) + self.assertIn('could not be used', warning) + finally: + import shutil + shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True) + USER_DIR = old + + def test_find_document(self): + a, b = self.job(name='job-new'), self.job(name='job-old') + b['parsed'] = {'ZZZ999': [{'doc_num': '500 100', 'accno': 'ZZZ999'}]} + jobs = [self.job('delnote', 'job-d'), a, b] + self.assertEqual(('job-new', 'HAR108'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, 'invoice'))) + self.assertEqual('job-new', find_document(jobs, 'invoice', '336770')[0]['name']) + self.assertEqual('job-old', find_document(jobs, 'invoice', '500100')[0]['name']) + self.assertEqual('job-old', find_document(jobs, 'invoice', 'zzz999')[0]['name']) + self.assertIsNone(find_document(jobs, 'invoice', 'nope')) + self.assertIsNone(find_document(jobs, 'statement')) + +if __name__ == "__main__": + unittest.main() diff --git a/main.py b/main.py index be22557..8fc6b7e 100755 --- a/main.py +++ b/main.py @@ -21,6 +21,7 @@ import time import pytz from settings import config, HOME +import emailtemplates from textutil import split_lines, load_job_pickle, load_user_pickles, PICKLE_PROTOCOL email_pickle = os.path.join(HOME, 'email.pickle') @@ -318,6 +319,59 @@ def printfn(query_string='', resp=None): traceback.print_exc(file=sys.stdout) return doMessage(title='Printing', message='Could not find document, problem printing! Source: %s sent to printer %s
    ' % (docf, query_string['printer'])) +def company_info(): + printing = lambda k: config.get('Printing', 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): + """Editor for the per document type email templates, with a preview against a real document. A POST + (postreq is not None) carries the edited text and one of the actions preview, save or revert.""" + params = dict((k, v[0]) for k, v in query_string.items()) + posted = postreq is not None + params.update(dict((k, v[0]) for k, v in (postreq or {}).items())) + kind = params.get('kind', 'invoice') + if kind not in emailtemplates.KINDS: + kind = 'invoice' + term = params.get('docnum', '').strip() + action = params.get('action', '') if posted else '' + + text, source = emailtemplates.load(kind) + message, errors = None, [] + if action == 'revert': + message = 'Reverted to the default %s template.' % emailtemplates.KINDS[kind].lower() if emailtemplates.revert(kind) else 'Already using the default template.' + text, source = emailtemplates.load(kind) + elif action in ('preview', 'save'): + text = params.get('template', '').replace('\r\n', '\n').replace('\r', '\n') + if action == 'save': + try: + emailtemplates.save(kind, text) + text, source = emailtemplates.load(kind) + message = 'Saved the %s template.' % emailtemplates.KINDS[kind].lower() + except emailtemplates.TemplateError as e: + errors = e.errors + + # preview: the newest document of this type, or the one whose document number / account matches the filter + found = emailtemplates.find_document(jobs, kind, term) + preview, preview_job, preview_acc, fields, names = None, None, None, [], [] + if not found: + preview_note = 'No %s document found%s.' % (emailtemplates.KINDS[kind].lower(), (' matching "%s"' % term) if term else '') + else: + preview_job, preview_acc = found + contacts = email_addresses.get(preview_acc, {}) + names = list(contacts.values()) + ctx = emailtemplates.build_context(preview_job, preview_acc, names=names, addresses=list(contacts.keys()), company=company_info()) + fields = emailtemplates.field_names(ctx['doc']) + preview_note = None + try: + preview = emailtemplates.render(text, ctx) + except emailtemplates.TemplateError as e: + errors = errors or e.errors + + return ( template_lookup.get_template("/settings_templates.html").render( + kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, user_path=emailtemplates.user_path(kind), + term=term, message=message, errors=errors, preview=preview, preview_note=preview_note, + preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields), 'text/html') + def pdf(query_string=dict(), resp=None): job = getJob(query_string) default_key = next(iter(job['groupfiles']))[0] @@ -349,7 +403,20 @@ def pdf(query_string=dict(), resp=None): except: raise - return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_template, email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') + # the suggested body comes from the template for this type of document, or the single default text + email_body_default, template_kind, template_warning = email_template, None, None + try: + rendered, template_kind, template_warning = emailtemplates.render_for_job( + job, key, names=list(email_dest.values()), addresses=list(email_dest.keys()), company=company_info()) + if rendered is not None: + email_body_default = rendered + except Exception: + traceback.print_exc(file=sys.stdout) + template_warning = 'The email template for this document could not be used; showing the default text.' + + return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, + template_kind=template_kind, template_warning=template_warning, + email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') def pdf_file(query_string='', resp=None): @@ -463,7 +530,8 @@ def htmlcol(rgb): '/print' : printfn, '/plaintext':plain, '/settings/email':settings_email, - '/settings/template':settings_template + '/settings/template':settings_template, + '/settings/templates':settings_templates } if __name__=="__main__": diff --git a/templates/invoice.mako b/templates/invoice.mako new file mode 100644 index 0000000..7eb5b2a --- /dev/null +++ b/templates/invoice.mako @@ -0,0 +1,9 @@ +## Email text offered when emailing an invoice. Copy changes into ~/printerface/templates/invoice.mako +## (or use Settings > Email Templates); this file is the default until you do. +## +## Available: ${doc.} for the invoice (doc.ourref, doc.doc_num, doc.accno, doc.tot_due, doc.customer ...), +## ${email.name}, ${job.name}, ${company.name}. If the account has several invoices in the print run, +## doc is the last one and "% for d in docs:" ... "% endfor" visits each of them. +To ${email.name} + +Please find your latest invoice ${doc.ourref} attached for account ${doc.accno}, for £${doc.tot_due}. diff --git a/templates/purchase.mako b/templates/purchase.mako new file mode 100644 index 0000000..3331626 --- /dev/null +++ b/templates/purchase.mako @@ -0,0 +1,10 @@ +## Email text offered when emailing a purchase order. See invoice.mako for the variables available. +## Purchase order fields include doc.doc_num, doc.accno, doc.orderdate, doc.custref, doc.ourcontact. +To ${email.name} + +Please find attached purchase order ${doc.doc_num}, dated ${doc.orderdate}, for account ${doc.accno}. + +Please confirm receipt and let us know when it will be ready for collection. + +Kind regards +${company.name} diff --git a/templates/statement.mako b/templates/statement.mako new file mode 100644 index 0000000..435f47a --- /dev/null +++ b/templates/statement.mako @@ -0,0 +1,10 @@ +## Email text offered when emailing a statement. See invoice.mako for the variables available. +## Statement fields include doc.accno, doc.date, doc.tot_topay, doc.age_curr, doc.age_1m, doc.age_2m, doc.age_3m. +To ${email.name} + +Please find attached your statement dated ${doc.date} for account ${doc.accno}. + +The balance to pay is £${doc.tot_topay}. + +Kind regards +${company.name} diff --git a/test_integration.py b/test_integration.py index af5fb01..5de0dc9 100644 --- a/test_integration.py +++ b/test_integration.py @@ -8,12 +8,14 @@ import shutil import socket import tempfile +import urllib.parse import threading import time import unittest import main import mailer +import emailtemplates from stationary import DocFormatter from lpdserver import LpdServer from httpserver import ToyHttpServer @@ -37,6 +39,7 @@ def make_invoice(doc_num='12345', acc='ACC001', pages=2): put(lines, base + 8, 12, 'ACME WINES LTD\n1 HIGH STREET\nLONDON') put(lines, base + 16, 0, acc) put(lines, base + 16, 9, 'PO-7') + put(lines, base + 16, 20, '289073') put(lines, base + 19, 0, 'B0321021\nB0308206') put(lines, base + 19, 19, 'BAUCHET Customer Label\nDRAPPIER Carte D\'Or') put(lines, base + 19, 55, '12\n6') @@ -79,6 +82,7 @@ def setUpClass(cls): main.pdfdir = os.path.join(cls.home, 'data', 'pdf') + os.sep main.formatter = DocFormatter(main.pdfdir) mailer.pickle_file = os.path.join(cls.home, 'mailer.pickle') + cls.old_user_dir, emailtemplates.USER_DIR = emailtemplates.USER_DIR, os.path.join(cls.home, 'templates') for x in [main.jobdir, main.pdfdir]: os.makedirs(x, exist_ok=True) cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0) @@ -94,6 +98,7 @@ def tearDownClass(cls): cls.thread.join() cls.lpd.close() cls.http.close() + emailtemplates.USER_DIR = cls.old_user_dir shutil.rmtree(cls.home, ignore_errors=True) def get(self, path, headers=None): @@ -104,8 +109,19 @@ def get(self, path, headers=None): conn.close() return r, body + def post(self, path, **fields): + conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) + body = urllib.parse.urlencode(fields).encode('utf-8') + conn.request('POST', path, body=body, headers={'Content-Type': 'application/x-www-form-urlencoded'}) + r = conn.getresponse() + data = r.read() + conn.close() + return r, data + def setUp(self): main.jobs.clear() + main.email_addresses.clear() + shutil.rmtree(emailtemplates.USER_DIR, ignore_errors=True) def send_invoice(self, **kw): before = len(main.jobs) @@ -231,6 +247,102 @@ def test_recent_json_ts_is_per_job(self): self.assertEqual(first['ts'].isoformat(), rows[first['name']]['ts']) self.assertEqual(second['ts'].isoformat(), rows[second['name']]['ts']) + INVOICE_TEXT = 'To %s\n\nPlease find your latest invoice 289073 attached for account ACC001, for \xa3123.45.' + + def test_compose_form_is_prefilled_from_the_invoice_template(self): + j = self.send_invoice() + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn((self.INVOICE_TEXT % 'Sir or Madam').encode('utf-8'), body) + self.assertIn(b'/settings/templates?kind=invoice&docnum=12345', body) + # with contacts on the account the greeting names them, and html in a name is escaped in the textarea + self.get('/settings/email?account=ACC001&email=a%40example.com&contact=Ann') + self.get('/settings/email?account=ACC001&email=b%40example.com&contact=Bob+%26+Co') + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertIn((self.INVOICE_TEXT % 'Ann and Bob & Co').encode('utf-8'), body) + + def test_documents_without_a_template_keep_the_default_text(self): + main.email_template = 'DEFAULT TEXT' + try: + lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJDelvnote\nldfA001testhost\n', make_invoice().encode('latin-1')) + deadline = time.time() + 20 + while not main.jobs and time.time() < deadline: + time.sleep(0.05) + r, body = self.get('/pdf?name=%s' % main.jobs[0]['name']) + self.assertEqual('delnote', main.jobs[0]['templ']) + self.assertIn(b'DEFAULT TEXT', body) + self.assertNotIn(b'/settings/templates?kind', body) + finally: + main.email_template = '' + + def test_template_editor_preview_save_and_revert(self): + j = self.send_invoice(doc_num='424242') + path = emailtemplates.user_path('invoice') + + r, body = self.get('/settings/templates?kind=invoice') + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(b'default template shipped with printerface', body) + self.assertIn(b'Please find your latest invoice 289073 attached', body) # preview of the newest invoice + for kind in ('purchase', 'statement'): + r, body = self.get('/settings/templates?kind=' + kind) + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(b'No ' + emailtemplates.KINDS[kind].lower().encode() + b' document found', body) + + # the filter picks the document; unknown numbers say so + r, body = self.get('/settings/templates?kind=invoice&docnum=424242') + self.assertIn(j['name'].encode(), body) + r, body = self.get('/settings/templates?kind=invoice&docnum=nope') + self.assertIn(b'No invoice document found matching', body) + self.assertIn(b'nope', body) + + # preview renders what is typed without saving it + r, body = self.post('/settings/templates', kind='invoice', action='preview', docnum='424242', + template='Hi ${email.name}, invoice ${doc.doc_num} for \xa3${doc.tot_due}.') + self.assertEqual(200, r.status) + self.assertIn('Hi Sir or Madam, invoice 424242 for \xa3123.45.'.encode('utf-8'), body) + self.assertFalse(os.path.exists(path)) + + # save writes the user template, and the compose form then uses it + r, body = self.post('/settings/templates', kind='invoice', action='save', docnum='', + template='Dear ${email.name}\r\nInvoice ${doc.doc_num}\r\n') + self.assertIn(b'Saved the invoice template', body) + self.assertIn(b'Using your customised template', body) + with open(path, encoding='utf-8') as f: + self.assertEqual('Dear ${email.name}\nInvoice ${doc.doc_num}\n', f.read()) + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertIn(b'Dear Sir or Madam\nInvoice 424242', body) + + # revert goes back to the shipped text + r, body = self.post('/settings/templates', kind='invoice', action='revert') + self.assertIn(b'Reverted to the default invoice template', body) + self.assertFalse(os.path.exists(path)) + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertIn((self.INVOICE_TEXT.replace('289073', '289073') % 'Sir or Madam').encode('utf-8'), body) + + def test_template_editor_refuses_templates_that_could_run_code(self): + self.send_invoice() + canary = os.path.join(emailtemplates.USER_DIR, '..', 'canary') + evil = [ + "${__import__('os').makedirs(%r)}" % canary, + "<%% import os; os.makedirs(%r) %%>" % canary, + "% import os", + "${doc.__class__}", + ] + for text in evil: + for action in ('preview', 'save'): + r, body = self.post('/settings/templates', kind='invoice', action=action, template=text) + self.assertEqual(200, r.status) + self.assertIn(b"This template can", body, text) + self.assertFalse(os.path.exists(emailtemplates.user_path('invoice')), text) + self.assertFalse(os.path.exists(canary), text) + # the kind comes from a fixed list, never from a path + r, body = self.post('/settings/templates', kind='../../etc/passwd', action='save', template='x') + self.assertEqual(200, r.status) + self.assertFalse(os.path.exists(os.path.join(emailtemplates.USER_DIR, '..', '..', 'etc'))) + def test_keepalive_two_requests_one_connection(self): self.send_invoice() conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) diff --git a/web/bootstrap.html b/web/bootstrap.html index f4ead61..49ac353 100644 --- a/web/bootstrap.html +++ b/web/bootstrap.html @@ -42,7 +42,8 @@ Settings
  • diff --git a/web/pdf.html b/web/pdf.html index 997a7f2..85823a1 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -96,8 +96,14 @@

    Compose Email

     
    + % if template_warning: +
    ${template_warning | h}
    + % endif + % if template_kind: + + % endif
    diff --git a/web/settings_template.html b/web/settings_template.html index 1f7c798..28ec71c 100644 --- a/web/settings_template.html +++ b/web/settings_template.html @@ -2,7 +2,8 @@ <%inherit file="bootstrap.html"/> <%block name="title">- Templates -

    Templates

    +

    Default Email Text

    +

    Used for documents that don't have their own email template.

    % if message:
    diff --git a/web/settings_templates.html b/web/settings_templates.html new file mode 100644 index 0000000..5b1a866 --- /dev/null +++ b/web/settings_templates.html @@ -0,0 +1,99 @@ +<%inherit file="bootstrap.html"/> +<%block name="title">- Email Templates + +

    Email Templates

    +

    The text offered when you email a document, one template per type of document. Other documents use the +default email text.

    + + + +% if message: +
    + + ${message | h} +
    +% endif + +% if errors: +
    + This template can't be used: +
      + % for e in errors: +
    • ${e | h}
    • + % endfor +
    + Only plain text, ${'${doc.field}'}, % for d in docs:, % if doc.field: and ## comments are allowed. +
    +% endif + +
    + + +
    +
    +

    + % if source == 'custom': + Using your customised template, saved as ${user_path | h}. + % else: + Using the default template shipped with printerface. Saving creates ${user_path | h}. + % endif +

    + +

    + + + % if source == 'custom': + + % endif +

    +
    + +
    +
    + Preview with + +
    + + % if preview_note: +
    ${preview_note | h}
    + % else: +

    + ${preview_job['name'] | h}, account ${preview_acc | h} + – open document
    + % if names: + Contacts: ${', '.join(names) | h} + % else: + No contacts are set for this account, so the name reads “Sir or Madam”. + % endif +

    + % if preview is not None: +
    ${preview | h}
    + % endif + % endif +
    +
    +
    + +

    Available fields

    +

    + ${'${email.name}'} ${'${email.address}'} + ${'${job.name}'} ${'${job.doctype}'} ${'${job.host}'} + ${'${company.name}'} ${'${company.email}'} ${'${company.website}'} +

    +% if fields: +

    From this document: + % for f in fields: + % if not f.startswith(('prod_', 'summ_')): + ${'${doc.' + f + '}'} + % endif + % endfor +

    +% endif +

    If an account has several documents in one print run, doc is the last of them; use +% for d in docs: … % endfor with ${'${d.field}'} to visit each one. +Add | trim to remove surrounding spaces.

    From b25a8fdbce00b05f06c5a956e6f723acf2485777 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:13:21 +0000 Subject: [PATCH 12/31] Drop the comment lines from the shipped email templates The editor already lists the available fields; the comments were just noise for users editing a template. Co-Authored-By: Claude Sonnet 5.5 --- templates/invoice.mako | 6 ------ templates/purchase.mako | 2 -- templates/statement.mako | 2 -- 3 files changed, 10 deletions(-) diff --git a/templates/invoice.mako b/templates/invoice.mako index 7eb5b2a..1f09c5e 100644 --- a/templates/invoice.mako +++ b/templates/invoice.mako @@ -1,9 +1,3 @@ -## Email text offered when emailing an invoice. Copy changes into ~/printerface/templates/invoice.mako -## (or use Settings > Email Templates); this file is the default until you do. -## -## Available: ${doc.} for the invoice (doc.ourref, doc.doc_num, doc.accno, doc.tot_due, doc.customer ...), -## ${email.name}, ${job.name}, ${company.name}. If the account has several invoices in the print run, -## doc is the last one and "% for d in docs:" ... "% endfor" visits each of them. To ${email.name} Please find your latest invoice ${doc.ourref} attached for account ${doc.accno}, for £${doc.tot_due}. diff --git a/templates/purchase.mako b/templates/purchase.mako index 3331626..b02cb9f 100644 --- a/templates/purchase.mako +++ b/templates/purchase.mako @@ -1,5 +1,3 @@ -## Email text offered when emailing a purchase order. See invoice.mako for the variables available. -## Purchase order fields include doc.doc_num, doc.accno, doc.orderdate, doc.custref, doc.ourcontact. To ${email.name} Please find attached purchase order ${doc.doc_num}, dated ${doc.orderdate}, for account ${doc.accno}. diff --git a/templates/statement.mako b/templates/statement.mako index 435f47a..b446c74 100644 --- a/templates/statement.mako +++ b/templates/statement.mako @@ -1,5 +1,3 @@ -## Email text offered when emailing a statement. See invoice.mako for the variables available. -## Statement fields include doc.accno, doc.date, doc.tot_topay, doc.age_curr, doc.age_1m, doc.age_2m, doc.age_3m. To ${email.name} Please find attached your statement dated ${doc.date} for account ${doc.accno}. From 2832e2df74324853945c37c2a48cf8724362b398 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:13:50 +0000 Subject: [PATCH 13/31] Ignore .venv Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 61c89c6..4c5c37c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.py[cod] venv +.venv From d79c4545e90734611ba139c096106bd66e941248 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:22:50 +0000 Subject: [PATCH 14/31] Fold the default email text into templates/default.mako: one editor The single email text for documents without their own template is now the 'default' template, edited in Settings > Email Templates alongside the others; the old Default Email Text page is removed. It can only use email and job (there are no document fields for those documents). The legacy text from email.pickle is saved to ~/printerface/templates/default.mako the first time this runs, once only. Every job now has a template, so the compose form no longer has a separate path for other documents. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 10 ++- emailtemplates.py | 148 ++++++++++++++++++++++++++++-------- main.py | 54 +++++++------ templates/default.mako | 3 + test_integration.py | 101 +++++++++++++++++++----- web/bootstrap.html | 1 - web/pdf.html | 4 +- web/settings_template.html | 24 ------ web/settings_templates.html | 22 +++++- 9 files changed, 257 insertions(+), 110 deletions(-) create mode 100644 templates/default.mako delete mode 100644 web/settings_template.html diff --git a/README.md b/README.md index 7d789ba..d470469 100644 --- a/README.md +++ b/README.md @@ -44,13 +44,19 @@ against a copy of the data on other ports (`lpd_port` and `http_port` in `defaul ### Email templates The text offered when emailing a document comes from a template per document type: `invoice`, `purchase` and -`statement` (other types use the single "Default Email Text" under Settings). Templates are Mako files. +`statement`, and `default` for every other kind of document (delivery notes, credit notes, reports...). +Templates are Mako files. `~/printerface/templates/.mako` is used if it exists, otherwise the copy shipped in `templates/` in the source, so an install that never customises a template follows the repository. Edit them under Settings > Email Templates, which previews the result against a real document (leave the filter blank for the newest, or enter a document number or account). -Variables: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`, +The default template only has `${email.name}`, `${email.address}` and `${job.name}`, `${job.doctype}`, +`${job.host}`, since printerface doesn't read the contents of those documents. Earlier releases kept one email +text in `email.pickle`; if there is one and no `default.mako` yet, it is saved as `~/printerface/templates/default.mako` +the first time this release starts (once only: reverting to the shipped default isn't undone by a restart). + +The other templates also have: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`, `doc.customer`, ... - the editor lists them), `${email.name}`, `${email.address}`, `${job.name}`, `${company.name}`. If an account has several documents in one print run `doc` is the last; use `% for d in docs:` ... `% endfor` to visit each. `% if doc.field:` / `% else:` / `% endif` and `##` comments work too. diff --git a/emailtemplates.py b/emailtemplates.py index d61fb87..3dc3db0 100644 --- a/emailtemplates.py +++ b/emailtemplates.py @@ -1,7 +1,8 @@ # Email body templates, one per document type. # # The text offered when emailing a document is rendered from a Mako template chosen by the type of the -# job (invoice, purchase order, statement). Templates are looked up in USER_DIR (~/printerface/templates) +# job: invoice, purchase order or statement, and 'default' for every other kind of document (credit notes, +# delivery notes, reports...). Templates are looked up in USER_DIR (~/printerface/templates) # first and fall back to the copies shipped with the source in SEED_DIR, so an install that has never # customised a template keeps following the repository. The web editor saves into USER_DIR. # @@ -19,10 +20,10 @@ from settings import BASE_DIR, HOME -KINDS = collections.OrderedDict([('invoice', 'Invoice'), ('purchase', 'Purchase order'), ('statement', 'Statement')]) -# job['templ'] -> template kind. Other document types (credit notes, delivery notes...) have no template of -# their own and keep using the single default email text. +KINDS = collections.OrderedDict([('invoice', 'Invoice'), ('purchase', 'Purchase order'), ('statement', 'Statement'), ('default', 'Default')]) +# job['templ'] -> template kind. Anything else uses 'default', which can only see the recipients and the job. KIND_FOR_TEMPL = {'invoice': 'invoice', 'purchase': 'purchase', 'statement': 'statement'} +DEFAULT = 'default' SEED_DIR = os.path.join(BASE_DIR, 'templates') USER_DIR = os.path.join(HOME, 'templates') @@ -84,7 +85,7 @@ def join_names(names): return ', '.join(names[:-1]) + ' and ' + names[-1] def kind_for_job(job): - return KIND_FOR_TEMPL.get(job.get('templ')) + return KIND_FOR_TEMPL.get(job.get('templ'), DEFAULT) def build_context(job, key, names=(), addresses=(), company=None): """The variables a template sees: @@ -92,27 +93,35 @@ def build_context(job, key, names=(), addresses=(), company=None): docs every document for the account in this print run, for '% for d in docs:' 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 [Printing] settings + The default template sees only email and job: the other document types have no fields we know of.""" + addresses = [a for a in addresses if a] + context = dict( + email=Fields({'name': join_names(names), 'address': addresses[0] if addresses else ''}), + job=Fields({'name': job.get('name', ''), 'doctype': job.get('doctype', ''), 'host': (job.get('control') or {}).get('H', '')})) + if kind_for_job(job) == DEFAULT: + return context parsed = job.get('parsed') or {} acc = account_for_key(parsed, key) docs = merge_documents(parsed[acc]) if acc else [] - addresses = [a for a in addresses if a] - return dict( - doc=Fields(docs[-1] if docs else {}), - docs=[Fields(d) for d in docs], - email=Fields({'name': join_names(names), 'address': addresses[0] if addresses else ''}), - job=Fields({'name': job.get('name', ''), 'doctype': job.get('doctype', ''), 'host': (job.get('control') or {}).get('H', '')}), - company=Fields(company or {})) + context.update(doc=Fields(docs[-1] if docs else {}), docs=[Fields(d) for d in docs], company=Fields(company or {})) + return context def find_document(jobs, kind, term=''): - """The filter behind the editor's preview. jobs is newest first. Returns (job, account) for the newest + """The filter behind the editor's preview. jobs is newest first. Returns (job, key) for the newest document of this kind whose document number, or account code, equals term (ignoring case and spaces), - or for the newest document of this kind if term is empty. None if there isn't one.""" + or for the newest document of this kind if term is empty. None if there isn't one. + For the default kind there are no document numbers: term matches the job name or the document type + (for example 'Delvnote'), and key is the job's first PDF group, as the compose form would use.""" norm = lambda s: re.sub(r'\s+', '', s or '').lower() want = norm(term) for job in jobs: if kind_for_job(job) != kind: continue + if kind == DEFAULT: + if not want or want in (norm(job.get('name')), norm(job.get('doctype'))): + return job, next(iter(job.get('groupfiles') or {}), ('',))[0] + continue for acc, pages in (job.get('parsed') or {}).items(): for d in merge_documents(pages): if not want or want in (norm(d.get('doc_num')), norm(d.get('accno'))): @@ -129,9 +138,11 @@ def find_document(jobs, kind, term=''): _ELSE = re.compile(r'^\s*%\s*else\s*:\s*$') _END = re.compile(r'^\s*%\s*(?:endif|endfor)\s*$') _ROOTS = frozenset(['doc', 'email', 'job', 'company']) +_DEFAULT_ROOTS = frozenset(['email', 'job']) -def validate(text): - """Returns a list of 'line N: problem' strings; empty if the template is safe to render.""" +def validate(text, kind=None): + """Returns a list of 'line N: problem' strings; empty if the template is safe to render as this kind + of template (the default template can only use email and job).""" errors = [] loop_vars = set() lines = text.replace('\r\n', '\n').replace('\r', '\n').split('\n') @@ -139,7 +150,7 @@ def validate(text): m = _FOR.match(line) if m: loop_vars.add(m.group(1)) - roots = _ROOTS | loop_vars + roots = (_DEFAULT_ROOTS if kind == DEFAULT else _ROOTS) | loop_vars def check_path(n, path, where): root = path.split('.')[0] @@ -159,6 +170,8 @@ def check_path(n, path, where): m = _IF.match(line) if m: check_path(n, m.group(1), 'the condition') + elif _FOR.match(line) and kind == DEFAULT: + errors.append('line %d: there are no documents to loop over in the default template' % n) elif not (_FOR.match(line) or _ELSE.match(line) or _END.match(line)): errors.append('line %d: only "%% for x in docs:", "%% if field:", "%% if not field:", "%% else:", "%% endif" and "%% endfor" are allowed' % n) continue @@ -179,8 +192,8 @@ def check_path(n, path, where): errors.append('template structure: %s' % (str(e).splitlines() or ['invalid'])[0]) return errors -def render(text, context): - errors = validate(text) +def render(text, context, kind=None): + errors = validate(text, kind) if errors: raise TemplateError(errors) try: @@ -215,7 +228,7 @@ def save(kind, text): text = text.replace('\r\n', '\n').replace('\r', '\n') if not text.endswith('\n'): text += '\n' - errors = validate(text) + errors = validate(text, kind) if errors: raise TemplateError(errors) path = user_path(kind) @@ -233,20 +246,36 @@ def revert(kind): return True return False +MIGRATED_MARKER = '.legacy-default-text-migrated' + +def migrate_legacy_default(text): + """Before there were per type templates a single email text was kept in email.pickle. Offer that text as + the default template, once, unless the user already has a default.mako. A marker file stops it coming back + if they later revert to the shipped default. Returns a message to log, or None if there was nothing to do.""" + marker = os.path.join(USER_DIR, MIGRATED_MARKER) + if not (text or '').strip() or os.path.exists(marker) or os.path.exists(user_path(DEFAULT)): + return None + try: + save(DEFAULT, text) + message = 'migrated the old email text to %s' % user_path(DEFAULT) + except TemplateError as e: + message = 'could not migrate the old email text (%s); it is still in email.pickle' % e + os.makedirs(USER_DIR, exist_ok=True) + open(marker, 'w').close() + return message + def render_for_job(job, key, names=(), addresses=(), company=None): - """(body, kind, warning) for the compose form, or (None, None, None) for a document type without its - own template. A user template that no longer renders falls back to the shipped one, with a warning.""" + """(body, kind, warning) for the compose form. A user template that no longer renders falls back to + the shipped one, with a warning.""" kind = kind_for_job(job) - if not kind: - return None, None, None context = build_context(job, key, names, addresses, company) text, source = load(kind) try: - return render(text, context), kind, None + return render(text, context, kind), kind, None except TemplateError as e: if source != 'custom': raise - body = render(open(seed_path(kind), encoding=ENCODING).read(), context) + body = render(open(seed_path(kind), encoding=ENCODING).read(), context, kind) return body, kind, 'Your %s template could not be used (%s); showing the default.' % (KINDS[kind].lower(), e) # ----------------------------------------------------------------------------------------------- tests @@ -291,19 +320,65 @@ def test_join_names(self): def test_shipped_templates_are_valid_and_the_invoice_text_is_as_specified(self): for kind in KINDS: text = open(seed_path(kind), encoding=ENCODING).read() - self.assertEqual([], validate(text), kind) + self.assertEqual([], validate(text, kind), kind) ctx = build_context(self.job(), 'HAR108', names=['Ann']) body = render(open(seed_path('invoice'), encoding=ENCODING).read(), ctx) self.assertEqual('To Ann\n\nPlease find your latest invoice 289099 attached for account HAR108, for \xa310.00.\n', body) def test_shipped_templates_render_with_no_data_at_all(self): for kind in KINDS: - body = render(open(seed_path(kind), encoding=ENCODING).read(), build_context({}, 'nothing')) + body = render(open(seed_path(kind), encoding=ENCODING).read(), build_context({'templ': kind}, 'nothing'), kind) self.assertTrue(body.startswith('To ' + NO_NAME), kind) - def test_other_document_types_have_no_template(self): - self.assertIsNone(render_for_job({'templ': 'delnote'}, 'X')[0]) - self.assertIsNone(render_for_job({'templ': None}, 'X')[0]) + def test_other_document_types_use_the_default_template(self): + for templ in ('delnote', 'crednote', 'picklist', None): + body, kind, warning = render_for_job({'templ': templ, 'name': 'job-9', 'doctype': 'Delvnote'}, 'X', ['Ann']) + self.assertEqual(('To Ann\n\nPlease find your document attached.\n', DEFAULT, None), (body, kind, warning), templ) + + def test_the_default_context_is_only_email_and_job(self): + ctx = build_context({'templ': 'delnote', 'name': 'job-9', 'doctype': 'Delvnote', 'control': {'H': 'PC1'}}, 'X', ['Ann'], ['a@b.c'], {'name': 'ABFW'}) + self.assertEqual(['email', 'job'], sorted(ctx)) + self.assertEqual(('Ann', 'a@b.c', 'job-9', 'Delvnote', 'PC1'), (ctx['email'].name, ctx['email'].address, ctx['job'].name, ctx['job'].doctype, ctx['job'].host)) + self.assertEqual([], validate('${email.name} ${job.doctype | trim}\n% if job.host:\nx\n% endif', DEFAULT)) + for text in ('${doc.ourref}', '${company.name}', '% for d in docs:\n% endfor', '% if doc.x:\n% endif'): + self.assertTrue(validate(text, DEFAULT), text) + if 'docs' not in text: + self.assertEqual([], validate(text, 'invoice'), text) # fine for a document type that has them + + def test_migrate_legacy_default_text_once(self): + import tempfile + global USER_DIR + old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates') + try: + self.assertIsNone(migrate_legacy_default('')) + self.assertIsNone(migrate_legacy_default(' \r\n')) + self.assertFalse(os.path.exists(user_path(DEFAULT))) + self.assertIn('migrated', migrate_legacy_default('Please find it attached.\r\n\r\nRegards,\r\nTony')) + self.assertEqual(('Please find it attached.\n\nRegards,\nTony\n', 'custom'), load(DEFAULT)) + # a user who reverts to the shipped text does not get the old text back at the next start + revert(DEFAULT) + self.assertIsNone(migrate_legacy_default('Please find it attached.')) + self.assertEqual('default', load(DEFAULT)[1]) + finally: + import shutil + shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True) + USER_DIR = old + + def test_migrate_never_overwrites_or_imports_unsafe_text(self): + import tempfile + global USER_DIR + old, USER_DIR = USER_DIR, os.path.join(tempfile.mkdtemp(prefix='printerface-test-'), 'templates') + try: + save(DEFAULT, 'mine') + self.assertIsNone(migrate_legacy_default('legacy')) + self.assertEqual('mine\n', load(DEFAULT)[0]) + revert(DEFAULT) + self.assertIn('could not migrate', migrate_legacy_default("${__import__('os')}")) + self.assertEqual('default', load(DEFAULT)[1]) + finally: + import shutil + shutil.rmtree(os.path.dirname(USER_DIR), ignore_errors=True) + USER_DIR = old def test_validate_accepts_the_safe_subset(self): ok = '''## a comment ${anything()} @@ -407,5 +482,14 @@ def test_find_document(self): self.assertIsNone(find_document(jobs, 'invoice', 'nope')) self.assertIsNone(find_document(jobs, 'statement')) + def test_find_document_for_the_default_kind_matches_job_name_or_type(self): + d1 = {'name': 'job-2', 'templ': 'delnote', 'doctype': 'Delvnote', 'groupfiles': {('accounts',): 'x.pdf'}} + d2 = {'name': 'job-1', 'templ': None, 'doctype': 'Batch', 'groupfiles': {('plain',): 'y.pdf'}} + jobs = [self.job('invoice', 'job-3'), d1, d2] + self.assertEqual(('job-2', 'accounts'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, DEFAULT))) + self.assertEqual(('job-1', 'plain'), (lambda r: (r[0]['name'], r[1]))(find_document(jobs, DEFAULT, 'batch'))) + self.assertEqual('job-1', find_document(jobs, DEFAULT, 'JOB-1')[0]['name']) + self.assertIsNone(find_document(jobs, DEFAULT, 'nope')) + if __name__ == "__main__": unittest.main() diff --git a/main.py b/main.py index 8fc6b7e..7d1431f 100755 --- a/main.py +++ b/main.py @@ -39,6 +39,8 @@ # seed some 'system' accounts email_accounts = { 'accounts': 'Accounts', 'plain': 'printerface', 'transport': 'Transport'} email_addresses = collections.defaultdict(dict) +# the single email text from before there were templates. Kept (and written back) so email.pickle keeps its +# layout, but only used to migrate it to templates/default.mako, see emailtemplates.migrate_legacy_default email_template = '' mainparser = DocParser() @@ -101,6 +103,10 @@ def recover(): except IOError: print('[control] email pickle load failed') + migrated = emailtemplates.migrate_legacy_default(email_template) + if migrated: + print('[control] ' + migrated) + # jobdir structured /YYYYMM/job-blah-blah.pickle. We want to avoid stating # more dated directories than necessary, so load the # xs = sorted([ x for x in os.listdir(jobdir) if x != 'raw']) @@ -294,21 +300,6 @@ def settings_email(query_string='', postreq=None, resp=None): return ( template_lookup.get_template("/settings_email.html").render(emails=email_list, warning=warning), 'text/html') -def settings_template(query_string='', postreq=None, resp=None): - global email_template - - print('query_string=%s' % query_string) - message = None - try: - template = query_string.get('template', None) - if template: - email_template = template[0] - saveEmails() - message = 'Thanks! Template updated' - except: - message = 'Ohno! Template failed' - return ( template_lookup.get_template("/settings_template.html").render(template=email_template, message=message), 'text/html') - def printfn(query_string='', resp=None): docf = getJobFile(query_string) if docf: @@ -338,7 +329,7 @@ def settings_templates(query_string='', postreq=None, resp=None): text, source = emailtemplates.load(kind) message, errors = None, [] if action == 'revert': - message = 'Reverted to the default %s template.' % emailtemplates.KINDS[kind].lower() if emailtemplates.revert(kind) else 'Already using the default template.' + message = 'Reverted to the shipped %s template.' % emailtemplates.KINDS[kind].lower() if emailtemplates.revert(kind) else 'Already using the shipped template.' text, source = emailtemplates.load(kind) elif action in ('preview', 'save'): text = params.get('template', '').replace('\r\n', '\n').replace('\r', '\n') @@ -351,26 +342,29 @@ def settings_templates(query_string='', postreq=None, resp=None): errors = e.errors # preview: the newest document of this type, or the one whose document number / account matches the filter + # (for the default template: the newest other document, or the job name / document type that matches) found = emailtemplates.find_document(jobs, kind, term) + is_default = kind == emailtemplates.DEFAULT preview, preview_job, preview_acc, fields, names = None, None, None, [], [] if not found: - preview_note = 'No %s document found%s.' % (emailtemplates.KINDS[kind].lower(), (' matching "%s"' % term) if term else '') + what = 'document' if is_default else '%s document' % emailtemplates.KINDS[kind].lower() + preview_note = 'No %s found%s.' % (what, (' matching "%s"' % term) if term else '') else: preview_job, preview_acc = found contacts = email_addresses.get(preview_acc, {}) names = list(contacts.values()) ctx = emailtemplates.build_context(preview_job, preview_acc, names=names, addresses=list(contacts.keys()), company=company_info()) - fields = emailtemplates.field_names(ctx['doc']) + fields = emailtemplates.field_names(ctx['doc']) if 'doc' in ctx else [] preview_note = None try: - preview = emailtemplates.render(text, ctx) + preview = emailtemplates.render(text, ctx, kind) except emailtemplates.TemplateError as e: errors = errors or e.errors return ( template_lookup.get_template("/settings_templates.html").render( kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, user_path=emailtemplates.user_path(kind), term=term, message=message, errors=errors, preview=preview, preview_note=preview_note, - preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields), 'text/html') + preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, is_default=is_default), 'text/html') def pdf(query_string=dict(), resp=None): job = getJob(query_string) @@ -403,19 +397,24 @@ def pdf(query_string=dict(), resp=None): except: raise - # the suggested body comes from the template for this type of document, or the single default text - email_body_default, template_kind, template_warning = email_template, None, None + # the suggested body comes from the template for this type of document (or the default template) + email_body_default, template_kind, template_warning, template_docnum = '', emailtemplates.DEFAULT, None, '' try: - rendered, template_kind, template_warning = emailtemplates.render_for_job( + email_body_default, template_kind, template_warning = emailtemplates.render_for_job( job, key, names=list(email_dest.values()), addresses=list(email_dest.keys()), company=company_info()) - if rendered is not None: - email_body_default = rendered except Exception: traceback.print_exc(file=sys.stdout) - template_warning = 'The email template for this document could not be used; showing the default text.' + template_warning = 'The email template for this document could not be used.' + # what the editor's preview filter should be set to so that it shows this document + if template_kind == emailtemplates.DEFAULT: + template_docnum = job.get('name', '') + else: + parsed = job.get('parsed') or {} + pages = parsed.get(emailtemplates.account_for_key(parsed, key)) or [{}] + template_docnum = pages[0].get('doc_num', '').strip() return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, - template_kind=template_kind, template_warning=template_warning, + template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') @@ -530,7 +529,6 @@ def htmlcol(rgb): '/print' : printfn, '/plaintext':plain, '/settings/email':settings_email, - '/settings/template':settings_template, '/settings/templates':settings_templates } diff --git a/templates/default.mako b/templates/default.mako new file mode 100644 index 0000000..6835f14 --- /dev/null +++ b/templates/default.mako @@ -0,0 +1,3 @@ +To ${email.name} + +Please find your document attached. diff --git a/test_integration.py b/test_integration.py index 5de0dc9..989f861 100644 --- a/test_integration.py +++ b/test_integration.py @@ -2,6 +2,7 @@ # over HTTP. Runs against a throwaway PRINTERFACE_HOME, never ~/printerface. import asyncore import http.client +import io import json import os import pickle @@ -123,9 +124,9 @@ def setUp(self): main.email_addresses.clear() shutil.rmtree(emailtemplates.USER_DIR, ignore_errors=True) - def send_invoice(self, **kw): + def send_invoice(self, jtype='Invoice', **kw): before = len(main.jobs) - lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJInvoice\nldfA001testhost\n', make_invoice(**kw).encode('latin-1')) + lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJ%s\nldfA001testhost\n' % jtype, make_invoice(**kw).encode('latin-1')) deadline = time.time() + 20 while len(main.jobs) == before and time.time() < deadline: time.sleep(0.05) @@ -204,7 +205,7 @@ def test_http_endpoints(self): r, body = self.get('/pdf_file?name=%s&key=ACC001&attach=1' % name) self.assertIn('attachment', r.getheader('Content-Disposition')) - for path in ['/home', '/sent', '/printers', '/settings/email', '/settings/template', + for path in ['/home', '/sent', '/printers', '/settings/email', '/settings/templates', '/pdf?name=' + name, '/debug?name=' + name, '/plaintext?name=' + name, '/']: r, body = self.get(path) self.assertEqual(200, r.status, path) @@ -262,19 +263,17 @@ def test_compose_form_is_prefilled_from_the_invoice_template(self): r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertIn((self.INVOICE_TEXT % 'Ann and Bob & Co').encode('utf-8'), body) - def test_documents_without_a_template_keep_the_default_text(self): - main.email_template = 'DEFAULT TEXT' - try: - lpr(self.lpd_port, 'RAW', 'Hlocalhost\nPtester\nJDelvnote\nldfA001testhost\n', make_invoice().encode('latin-1')) - deadline = time.time() + 20 - while not main.jobs and time.time() < deadline: - time.sleep(0.05) - r, body = self.get('/pdf?name=%s' % main.jobs[0]['name']) - self.assertEqual('delnote', main.jobs[0]['templ']) - self.assertIn(b'DEFAULT TEXT', body) - self.assertNotIn(b'/settings/templates?kind', body) - finally: - main.email_template = '' + DEFAULT_TEXT = 'To %s\n\nPlease find your document attached.' + + def test_other_documents_use_the_default_template(self): + j = self.send_invoice('Delvnote') + self.assertEqual('delnote', j['templ']) + r, body = self.get('/pdf?name=' + j['name']) + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn((self.DEFAULT_TEXT % 'Sir or Madam').encode('utf-8'), body) + self.assertIn(('/settings/templates?kind=default&docnum=' + j['name']).encode(), body) + self.assertIn(b'Edit the default email template', body) def test_template_editor_preview_save_and_revert(self): j = self.send_invoice(doc_num='424242') @@ -317,7 +316,7 @@ def test_template_editor_preview_save_and_revert(self): # revert goes back to the shipped text r, body = self.post('/settings/templates', kind='invoice', action='revert') - self.assertIn(b'Reverted to the default invoice template', body) + self.assertIn(b'Reverted to the shipped invoice template', body) self.assertFalse(os.path.exists(path)) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertIn((self.INVOICE_TEXT.replace('289073', '289073') % 'Sir or Madam').encode('utf-8'), body) @@ -343,6 +342,74 @@ def test_template_editor_refuses_templates_that_could_run_code(self): self.assertEqual(200, r.status) self.assertFalse(os.path.exists(os.path.join(emailtemplates.USER_DIR, '..', '..', 'etc'))) + def test_default_template_editor(self): + self.send_invoice(doc_num='111') # an invoice does not count as "another document" + r, body = self.get('/settings/templates?kind=default') + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(b'No document found', body) + j = self.send_invoice('Delvnote') + r, body = self.get('/settings/templates?kind=default') + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(j['name'].encode(), body) + self.assertIn(b'Delvnote', body) + self.assertIn(b'job name or document type', body) + self.assertNotIn(b'${company.name}', body) # not available to the default template + self.assertNotIn(b'${doc.', body) + self.assertIn(b'Default', body) # the tab + # the filter takes a job name or a document type + for term in (j['name'], 'delvnote'): + r, body = self.get('/settings/templates?kind=default&docnum=' + term) + self.assertIn(j['name'].encode(), body, term) + r, body = self.get('/settings/templates?kind=default&docnum=Nonesuch') + self.assertIn(b'No document found matching', body) + + r, body = self.post('/settings/templates', kind='default', action='preview', docnum='', template='${job.doctype} for ${email.name}') + self.assertIn(b'Delvnote for Sir or Madam', body) + # only email and job exist here + for text in ('${doc.ourref}', '${company.name}', '% for d in docs:\n% endfor'): + r, body = self.post('/settings/templates', kind='default', action='save', template=text) + self.assertIn(b"This template can", body, text) + self.assertFalse(os.path.exists(emailtemplates.user_path('default')), text) + r, body = self.post('/settings/templates', kind='default', action='save', template='Hello ${email.name}, re ${job.doctype}') + self.assertIn(b'Saved the default template', body) + r, body = self.get('/pdf?name=' + j['name']) + self.assertIn(b'Hello Sir or Madam, re Delvnote', body) + r, body = self.post('/settings/templates', kind='default', action='revert') + self.assertIn(b'Reverted to the shipped default template', body) + r, body = self.get('/pdf?name=' + j['name']) + self.assertIn((self.DEFAULT_TEXT % 'Sir or Madam').encode('utf-8'), body) + + def test_the_old_single_email_text_is_migrated_once_at_startup(self): + import contextlib + j = self.send_invoice('Delvnote') + # the old text lives in email.pickle, which recover() reads back at startup + main.email_template = 'Please find it attached.\r\n\r\nRegards,\r\nTony Page' + try: + with contextlib.redirect_stdout(io.StringIO()): + main.saveEmails() + main.jobs.clear(); main.recover() + r, body = self.get('/pdf?name=' + j['name']) + self.assertIn(b'Please find it attached.\n\nRegards,\nTony Page', body) + with open(emailtemplates.user_path('default'), encoding='utf-8') as f: + self.assertEqual('Please find it attached.\n\nRegards,\nTony Page\n', f.read()) + # reverting is not undone by the next restart + self.post('/settings/templates', kind='default', action='revert') + with contextlib.redirect_stdout(io.StringIO()): + main.jobs.clear(); main.recover() + self.assertFalse(os.path.exists(emailtemplates.user_path('default'))) + finally: + main.email_template = '' + with contextlib.redirect_stdout(io.StringIO()): + main.saveEmails() + + def test_the_old_default_text_editor_is_gone(self): + r, body = self.get('/settings/template') + self.assertEqual(404, r.status) + r, body = self.get('/home') + self.assertNotIn(b'Default Email Text', body) + self.assertIn(b'/settings/templates', body) + def test_keepalive_two_requests_one_connection(self): self.send_invoice() conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) diff --git a/web/bootstrap.html b/web/bootstrap.html index 49ac353..daa3a41 100644 --- a/web/bootstrap.html +++ b/web/bootstrap.html @@ -43,7 +43,6 @@ diff --git a/web/pdf.html b/web/pdf.html index 85823a1..76db9a6 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -101,9 +101,7 @@

    Compose Email

    % if template_warning:
    ${template_warning | h}
    % endif - % if template_kind: - - % endif +
    diff --git a/web/settings_template.html b/web/settings_template.html deleted file mode 100644 index 28ec71c..0000000 --- a/web/settings_template.html +++ /dev/null @@ -1,24 +0,0 @@ - -<%inherit file="bootstrap.html"/> -<%block name="title">- Templates - -

    Default Email Text

    -

    Used for documents that don't have their own email template.

    - -% if message: -
    - - ${message} -
    -% endif - -
    - -
    - - - - -
    - diff --git a/web/settings_templates.html b/web/settings_templates.html index 5b1a866..642907d 100644 --- a/web/settings_templates.html +++ b/web/settings_templates.html @@ -2,8 +2,8 @@ <%block name="title">- Email Templates

    Email Templates

    -

    The text offered when you email a document, one template per type of document. Other documents use the -default email text.

    +

    The text offered when you email a document. Invoices, purchase orders and statements have a template each; +every other document (delivery notes, credit notes, reports…) uses the Default one.

    + % if is_default: + Only plain text, ${'${email.name}'}, ${'${job.name}'}, % if job.host: and ## comments are allowed. + % else: Only plain text, ${'${doc.field}'}, % for d in docs:, % if doc.field: and ## comments are allowed. + % endif % endif @@ -56,15 +60,20 @@

    Email Templates

    Preview with - +
    % if preview_note:
    ${preview_note | h}
    % else:

    + % if is_default: + ${preview_job['name'] | h}, ${preview_job['doctype'] | h} + – open document
    + % else: ${preview_job['name'] | h}, account ${preview_acc | h} – open document
    + % endif % if names: Contacts: ${', '.join(names) | h} % else: @@ -83,7 +92,9 @@

    Available fields

    ${'${email.name}'} ${'${email.address}'} ${'${job.name}'} ${'${job.doctype}'} ${'${job.host}'} + % if not is_default: ${'${company.name}'} ${'${company.email}'} ${'${company.website}'} + % endif

    % if fields:

    From this document: @@ -94,6 +105,11 @@

    Available fields

    % endfor

    % endif +% if is_default: +

    The default template is used for documents whose contents printerface doesn't read, so only the recipients +and the job are available. Add | trim to remove surrounding spaces.

    +% else:

    If an account has several documents in one print run, doc is the last of them; use % for d in docs: … % endfor with ${'${d.field}'} to visit each one. Add | trim to remove surrounding spaces.

    +% endif From d98718f1a30b5daa4cf2d51e782f274f15d16ff4 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:43:44 +0000 Subject: [PATCH 15/31] Compose form: re-render the email text when contacts are ticked or unticked ${email.name} and ${email.address} depend on the recipients, so the form now asks /email_body (read only) for the text for the ticked contacts and updates the textarea. Text the user has edited is kept, with a notice offering to replace it, and answers that arrive out of order are ignored. Also escape contact names and addresses where they are shown and used as checkbox values. The script is tested with node (skipped where node is absent) and the endpoint and page wiring in test_integration.py. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +++ main.py | 18 ++++++++- test_compose.js | 91 +++++++++++++++++++++++++++++++++++++++++++++ test_compose_js.py | 16 ++++++++ test_integration.py | 36 ++++++++++++++++++ web/js/compose.js | 84 +++++++++++++++++++++++++++++++++++++++++ web/pdf.html | 10 ++++- 7 files changed, 257 insertions(+), 3 deletions(-) create mode 100644 test_compose.js create mode 100644 test_compose_js.py create mode 100644 web/js/compose.js diff --git a/README.md b/README.md index d470469..e2c6778 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,11 @@ The default template only has `${email.name}`, `${email.address}` and `${job.nam text in `email.pickle`; if there is one and no `default.mako` yet, it is saved as `~/printerface/templates/default.mako` the first time this release starts (once only: reverting to the shipped default isn't undone by a restart). +In the email compose form, ticking or unticking a contact re-renders the suggested text for the chosen recipients +(`${email.name}` and `${email.address}` follow the ticks). Text you have already edited is kept, with a notice +offering to replace it. The form's script is `web/js/compose.js`; `test_compose.js` tests it with node and is skipped +where node isn't installed. + The other templates also have: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`, `doc.customer`, ... - the editor lists them), `${email.name}`, `${email.address}`, `${job.name}`, `${company.name}`. If an account has several documents in one print run `doc` is the last; use diff --git a/main.py b/main.py index 7d1431f..1af49fd 100755 --- a/main.py +++ b/main.py @@ -14,6 +14,7 @@ from printing import getPrinters, printFile import sys, pickle +import urllib.parse from io import StringIO import collections import traceback @@ -366,6 +367,19 @@ def settings_templates(query_string='', postreq=None, resp=None): term=term, message=message, errors=errors, preview=preview, preview_note=preview_note, preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, is_default=is_default), 'text/html') +def email_body(query_string=dict(), resp=None): + """The suggested email text for a document if only the contacts whose addresses are in 'em' are + recipients. The compose form asks for this when contacts are ticked or unticked, since a template can use + the recipients' names. No 'em' means no recipients. Answers {"body": ..., "warning": ...}.""" + job = getJob(query_string) + default_key = next(iter(job.get('groupfiles') or {}), ('',))[0] + key = query_string.get('key', [default_key])[0] + known = email_addresses.get(key, {}) + ticked = query_string.get('em', []) + body, kind, warning = emailtemplates.render_for_job( + job, key, names=[known[a] for a in ticked if a in known], addresses=ticked, company=company_info()) + return json.dumps({'body': body, 'warning': warning}), 'text/json' + def pdf(query_string=dict(), resp=None): job = getJob(query_string) default_key = next(iter(job['groupfiles']))[0] @@ -415,6 +429,7 @@ def pdf(query_string=dict(), resp=None): return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, + email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') @@ -529,7 +544,8 @@ def htmlcol(rgb): '/print' : printfn, '/plaintext':plain, '/settings/email':settings_email, - '/settings/templates':settings_templates + '/settings/templates':settings_templates, + '/email_body':email_body } if __name__=="__main__": diff --git a/test_compose.js b/test_compose.js new file mode 100644 index 0000000..235daa8 --- /dev/null +++ b/test_compose.js @@ -0,0 +1,91 @@ +// Tests for web/js/compose.js with a minimal stand-in for the DOM. Run by test_compose_js.py, or: node test_compose.js +const assert = require('assert'); +const {init} = require('./web/js/compose.js'); + +function element(props) { + const handlers = {}; + return Object.assign({ + style: {}, + addEventListener(type, fn) { (handlers[type] = handlers[type] || []).push(fn); }, + fire(type) { (handlers[type] || []).forEach(fn => fn({preventDefault() {}})); }, + getAttribute(name) { return (this.attrs || {})[name]; }, + }, props); +} + +function setup(addresses, text, url = '/email_body?name=job-1&key=ACC1') { + const boxes = addresses.map(a => element({name: 'em', value: a, checked: true})); + const area = element({value: text, attrs: url ? {'data-url': url} : {}}); + const notice = element({style: {display: 'none'}}); + const reapply = element({}); + const byId = {inputBody: area, bodyNotice: notice, bodyReapply: reapply}; + const doc = {getElementById: id => byId[id], querySelectorAll: () => boxes}; + const requests = []; + const fetchFn = u => new Promise(resolve => requests.push({url: u, answer: body => resolve({json: () => Promise.resolve({body})})})); + return {boxes, area, notice, reapply, requests, api: init(doc, fetchFn)}; +} +const settle = () => new Promise(resolve => setImmediate(resolve)); + +(async () => { + // ticking and unticking asks the server with exactly the ticked addresses, in page order, and uses the answer + let t = setup(['ann@x.com', 'bob+co@x.com'], 'To Ann and Bob\n'); + t.boxes[0].checked = false; + t.boxes[0].fire('change'); + assert.strictEqual(t.requests.length, 1); + assert.strictEqual(t.requests[0].url, '/email_body?name=job-1&key=ACC1&em=bob%2Bco%40x.com'); + t.requests[0].answer('To Bob\n'); + await settle(); + assert.strictEqual(t.area.value, 'To Bob\n'); + assert.strictEqual(t.notice.style.display, 'none'); + + // nothing ticked: no em at all + t.boxes[1].checked = false; + t.boxes[1].fire('change'); + assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1'); + t.requests[1].answer('To Sir or Madam\n'); + await settle(); + assert.strictEqual(t.area.value, 'To Sir or Madam\n'); + + // edited text is kept, with a notice; the link replaces it using the current ticks + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); + t.area.value = 'To Ann and Bob\nmy own words\n'; + t.boxes[1].checked = false; + t.boxes[1].fire('change'); + t.requests[0].answer('To Ann\n'); + await settle(); + assert.strictEqual(t.area.value, 'To Ann and Bob\nmy own words\n'); + assert.strictEqual(t.notice.style.display, ''); + t.reapply.fire('click'); + assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1&em=ann%40x.com'); + t.requests[1].answer('To Ann\n'); + await settle(); + assert.strictEqual(t.area.value, 'To Ann\n'); + assert.strictEqual(t.notice.style.display, 'none'); + + // text that was refreshed by us is not "edited": a second tick updates it again without a notice + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); + t.boxes[0].checked = false; t.boxes[0].fire('change'); t.requests[0].answer('To Bob\n'); await settle(); + t.boxes[0].checked = true; t.boxes[0].fire('change'); t.requests[1].answer('To Ann and Bob\n'); await settle(); + assert.strictEqual(t.area.value, 'To Ann and Bob\n'); + assert.strictEqual(t.notice.style.display, 'none'); + + // answers arriving out of order: only the answer to the latest tick is used + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); + t.boxes[0].checked = false; t.boxes[0].fire('change'); + t.boxes[1].checked = false; t.boxes[1].fire('change'); + t.requests[1].answer('To Sir or Madam\n'); + await settle(); + t.requests[0].answer('To Bob\n'); + await settle(); + assert.strictEqual(t.area.value, 'To Sir or Madam\n'); + + // a failed request leaves the text alone + t = setup(['ann@x.com'], 'To Ann\n'); + const failing = {getElementById: id => ({inputBody: t.area}[id]), querySelectorAll: () => t.boxes}; + const api = init(failing, () => Promise.reject(new Error('offline'))); + await api.refresh(false); + assert.strictEqual(t.area.value, 'To Ann\n'); + + // a page without the compose form is left alone + assert.strictEqual(setup(['a@x.com'], 'x', null).api, undefined); + console.log('compose.js: all tests passed'); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/test_compose_js.py b/test_compose_js.py new file mode 100644 index 0000000..eefbcf3 --- /dev/null +++ b/test_compose_js.py @@ -0,0 +1,16 @@ +# Runs the node tests for web/js/compose.js (skipped where node isn't installed, e.g. the docker image). +import os +import shutil +import subprocess +import unittest + +@unittest.skipUnless(shutil.which('node'), 'node is not installed') +class TestComposeJs(unittest.TestCase): + def test_compose_js(self): + here = os.path.dirname(os.path.abspath(__file__)) + r = subprocess.run(['node', 'test_compose.js'], cwd=here, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) + self.assertEqual(0, r.returncode, r.stdout) + self.assertIn('all tests passed', r.stdout) + +if __name__ == "__main__": + unittest.main() diff --git a/test_integration.py b/test_integration.py index 989f861..39e75f2 100644 --- a/test_integration.py +++ b/test_integration.py @@ -342,6 +342,42 @@ def test_template_editor_refuses_templates_that_could_run_code(self): self.assertEqual(200, r.status) self.assertFalse(os.path.exists(os.path.join(emailtemplates.USER_DIR, '..', '..', 'etc'))) + def test_email_body_follows_the_ticked_contacts(self): + j = self.send_invoice() + self.get('/settings/email?account=ACC001&email=ann%40x.com&contact=Ann') + self.get('/settings/email?account=ACC001&email=bob%40x.com&contact=Bob') + + def body(*ticked): + query = ['name=' + j['name'], 'key=ACC001'] + ['em=' + urllib.parse.quote(e) for e in ticked] + r, data = self.get('/email_body?' + '&'.join(query)) + self.assertEqual(200, r.status) + self.assertTrue(r.getheader('Content-Type').startswith('text/json')) + answer = json.loads(data.decode('utf-8')) + self.assertIsNone(answer['warning']) + return answer['body'] + + self.assertTrue(body('ann@x.com', 'bob@x.com').startswith('To Ann and Bob\n\nPlease find your latest invoice 289073')) + self.assertTrue(body('bob@x.com').startswith('To Bob\n\nPlease find')) + self.assertTrue(body().startswith('To Sir or Madam\n\nPlease find')) # nobody ticked + self.assertTrue(body('stranger@x.com').startswith('To Sir or Madam\n')) # not in the address book: no name to use + self.post('/settings/templates', kind='invoice', action='save', template='${email.name} <${email.address}>') + self.assertEqual('Bob and Ann \n', body('bob@x.com', 'ann@x.com')) # the first ticked address + self.assertEqual('Sir or Madam <>\n', body()) + + def test_compose_form_is_wired_for_live_updates(self): + j = self.send_invoice() + self.get('/settings/email?account=ACC001&email=bob%40x.com&contact=Bob+%26+Co') + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(('data-url="/email_body?name=%s&key=ACC001"' % j['name']).encode(), body) + self.assertIn(b'id="bodyNotice"', body) + self.assertIn(b'', body) + # contact names and addresses are escaped where they are shown and where they are values + self.assertIn(b' Bob & Co', body) + r, js = self.get('/js/compose.js') + self.assertEqual(200, r.status) + self.assertIn('javascript', r.getheader('Content-Type')) + def test_default_template_editor(self): self.send_invoice(doc_num='111') # an invoice does not count as "another document" r, body = self.get('/settings/templates?kind=default') diff --git a/web/js/compose.js b/web/js/compose.js new file mode 100644 index 0000000..bc5f4b6 --- /dev/null +++ b/web/js/compose.js @@ -0,0 +1,84 @@ +// Email compose form: when a contact is ticked or unticked the suggested text is re-rendered by the server, +// since the template can use the recipients (${email.name}). Text the user has already edited is never +// replaced silently: it is kept, and a notice offers to replace it. +(function () { + function init(doc, fetchFn) { + var area = doc.getElementById('inputBody'); + if (!area || !area.getAttribute('data-url')) { + return; + } + var boxes = doc.querySelectorAll('input[name="em"]'); + var notice = doc.getElementById('bodyNotice'); + var reapply = doc.getElementById('bodyReapply'); + var lastRendered = area.value; // what the server gave us; anything else in the box was typed + var latest = 0; + + function selected() { + var out = []; + for (var i = 0; i < boxes.length; i++) { + if (boxes[i].checked) { + out.push(boxes[i].value); + } + } + return out; + } + + function url() { + var u = area.getAttribute('data-url'); + selected().forEach(function (address) { + u += '&em=' + encodeURIComponent(address); + }); + return u; + } + + function showNotice(visible) { + if (notice) { + notice.style.display = visible ? '' : 'none'; + } + } + + function refresh(replaceEdits) { + var mine = ++latest; + return fetchFn(url()).then(function (r) { + return r.json(); + }).then(function (d) { + if (mine !== latest) { + return; // a later tick has asked again; its answer is the one that counts + } + if (area.value !== lastRendered && !replaceEdits) { + showNotice(true); + return; + } + area.value = d.body; + lastRendered = area.value; + showNotice(false); + }).catch(function () { + // leave the text as it is; the user can still edit it by hand + }); + } + + for (var i = 0; i < boxes.length; i++) { + boxes[i].addEventListener('change', function () { + refresh(false); + }); + } + if (reapply) { + reapply.addEventListener('click', function (event) { + if (event && event.preventDefault) { + event.preventDefault(); + } + refresh(true); + }); + } + return {refresh: refresh}; + } + + if (typeof window !== 'undefined') { + window.addEventListener('DOMContentLoaded', function () { + init(document, window.fetch.bind(window)); + }); + } + if (typeof module !== 'undefined') { + module.exports = {init: init}; + } +})(); diff --git a/web/pdf.html b/web/pdf.html index 76db9a6..5bca09f 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -80,7 +80,7 @@

    Compose Email

    % for (em,cn) in email_dest.items(): - + % endfor
    @@ -95,9 +95,13 @@

    Compose Email

     
    - + % if template_warning:
    ${template_warning | h}
    % endif @@ -114,3 +118,5 @@

    Compose Email

    + + From 0afb17936114433aefd1f5054ea7e5a5aa92fff6 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 12:58:55 +0000 Subject: [PATCH 16/31] Email templates: the first rendered line is the subject, the rest is the body The compose form's Subject box is now filled from the template (and re-rendered, with the text, when contacts are ticked or unticked; a field the user has edited is kept). The shipped templates start with a subject line, for example 'Invoice ${doc.ourref} from ${company.name}'. The editor previews the subject separately and says when the first line renders empty. Migrating the old single email text gives it the shipped default's subject. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 4 ++ emailtemplates.py | 75 ++++++++++++++++++++++------ main.py | 23 +++++---- templates/default.mako | 2 + templates/invoice.mako | 2 + templates/purchase.mako | 2 + templates/statement.mako | 2 + test_compose.js | 99 +++++++++++++++++++++++++------------ test_integration.py | 33 ++++++++++--- web/js/compose.js | 34 ++++++++----- web/pdf.html | 6 +-- web/settings_templates.html | 9 +++- 12 files changed, 212 insertions(+), 79 deletions(-) diff --git a/README.md b/README.md index e2c6778..a83f8f0 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,10 @@ source, so an install that never customises a template follows the repository. E Settings > Email Templates, which previews the result against a real document (leave the filter blank for the newest, or enter a document number or account). +The first line of the rendered template is the email's subject and the rest is the body (blank lines between +them don't count), so subjects can be generated from the document like the rest of the text, for example +`Invoice ${doc.ourref} from ${company.name}`. Both are filled into the compose form. + The default template only has `${email.name}`, `${email.address}` and `${job.name}`, `${job.doctype}`, `${job.host}`, since printerface doesn't read the contents of those documents. Earlier releases kept one email text in `email.pickle`; if there is one and no `default.mako` yet, it is saved as `~/printerface/templates/default.mako` diff --git a/emailtemplates.py b/emailtemplates.py index 3dc3db0..dec6074 100644 --- a/emailtemplates.py +++ b/emailtemplates.py @@ -11,6 +11,9 @@ # plain text, ${field.lookups}, 'for ... in docs', simple 'if' tests and comments. There are no calls, no # <% %> blocks, no operators and no names starting with an underscore, so a template cannot reach # anything but the document data it is given. +# +# The first line of the rendered text is the email's subject; the rest is the body. So a template can +# compute the subject from the document as well, and subjects are generated mechanically. import collections import os import re @@ -192,6 +195,15 @@ def check_path(n, path, where): errors.append('template structure: %s' % (str(e).splitlines() or ['invalid'])[0]) return errors +Message = collections.namedtuple('Message', 'subject body') + +def split_subject(rendered): + """The first line of the rendered text is the subject, the rest is the body. Blank lines between them + (a separator, for readability in the template) are not part of the body.""" + first, _, rest = rendered.partition('\n') + rest = re.sub(r'\A(?:[ \t]*\n)+', '', rest) + return Message(first.strip(), (rest.rstrip() + '\n') if rest.strip() else '') + def render(text, context, kind=None): errors = validate(text, kind) if errors: @@ -202,6 +214,9 @@ def render(text, context, kind=None): raise TemplateError(['%s: %s' % (type(e).__name__, e)]) return out.rstrip() + '\n' +def render_message(text, context, kind=None): + return split_subject(render(text, context, kind)) + # ------------------------------------------------------------------------------------------ storage def _check_kind(kind): @@ -256,7 +271,10 @@ def migrate_legacy_default(text): if not (text or '').strip() or os.path.exists(marker) or os.path.exists(user_path(DEFAULT)): return None try: - save(DEFAULT, text) + # the old text had no subject line (the user typed one in); give it the shipped default's + with open(seed_path(DEFAULT), encoding=ENCODING) as f: + subject_line = f.readline().rstrip('\n') + save(DEFAULT, subject_line + '\n\n' + text.lstrip('\r\n')) message = 'migrated the old email text to %s' % user_path(DEFAULT) except TemplateError as e: message = 'could not migrate the old email text (%s); it is still in email.pickle' % e @@ -265,18 +283,18 @@ def migrate_legacy_default(text): return message def render_for_job(job, key, names=(), addresses=(), company=None): - """(body, kind, warning) for the compose form. A user template that no longer renders falls back to - the shipped one, with a warning.""" + """(Message(subject, body), kind, warning) for the compose form. A user template that no longer renders + falls back to the shipped one, with a warning.""" kind = kind_for_job(job) context = build_context(job, key, names, addresses, company) text, source = load(kind) try: - return render(text, context, kind), kind, None + return render_message(text, context, kind), kind, None except TemplateError as e: if source != 'custom': raise - body = render(open(seed_path(kind), encoding=ENCODING).read(), context, kind) - return body, kind, 'Your %s template could not be used (%s); showing the default.' % (KINDS[kind].lower(), e) + message = render_message(open(seed_path(kind), encoding=ENCODING).read(), context, kind) + return message, kind, 'Your %s template could not be used (%s); showing the default.' % (KINDS[kind].lower(), e) # ----------------------------------------------------------------------------------------------- tests @@ -321,19 +339,21 @@ def test_shipped_templates_are_valid_and_the_invoice_text_is_as_specified(self): for kind in KINDS: text = open(seed_path(kind), encoding=ENCODING).read() self.assertEqual([], validate(text, kind), kind) - ctx = build_context(self.job(), 'HAR108', names=['Ann']) - body = render(open(seed_path('invoice'), encoding=ENCODING).read(), ctx) - self.assertEqual('To Ann\n\nPlease find your latest invoice 289099 attached for account HAR108, for \xa310.00.\n', body) + ctx = build_context(self.job(), 'HAR108', names=['Ann'], company={'name': 'ABFW'}) + message = render_message(open(seed_path('invoice'), encoding=ENCODING).read(), ctx) + self.assertEqual('Invoice 289099 from ABFW', message.subject) + self.assertEqual('To Ann\n\nPlease find your latest invoice 289099 attached for account HAR108, for \xa310.00.\n', message.body) def test_shipped_templates_render_with_no_data_at_all(self): for kind in KINDS: - body = render(open(seed_path(kind), encoding=ENCODING).read(), build_context({'templ': kind}, 'nothing'), kind) - self.assertTrue(body.startswith('To ' + NO_NAME), kind) + message = render_message(open(seed_path(kind), encoding=ENCODING).read(), build_context({'templ': kind}, 'nothing'), kind) + self.assertTrue(message.body.startswith('To ' + NO_NAME), kind) + self.assertTrue(message.subject, kind) def test_other_document_types_use_the_default_template(self): for templ in ('delnote', 'crednote', 'picklist', None): - body, kind, warning = render_for_job({'templ': templ, 'name': 'job-9', 'doctype': 'Delvnote'}, 'X', ['Ann']) - self.assertEqual(('To Ann\n\nPlease find your document attached.\n', DEFAULT, None), (body, kind, warning), templ) + message, kind, warning = render_for_job({'templ': templ, 'name': 'job-9', 'doctype': 'Delvnote'}, 'X', ['Ann']) + self.assertEqual((('Document attached', 'To Ann\n\nPlease find your document attached.\n'), DEFAULT, None), (tuple(message), kind, warning), templ) def test_the_default_context_is_only_email_and_job(self): ctx = build_context({'templ': 'delnote', 'name': 'job-9', 'doctype': 'Delvnote', 'control': {'H': 'PC1'}}, 'X', ['Ann'], ['a@b.c'], {'name': 'ABFW'}) @@ -354,7 +374,9 @@ def test_migrate_legacy_default_text_once(self): self.assertIsNone(migrate_legacy_default(' \r\n')) self.assertFalse(os.path.exists(user_path(DEFAULT))) self.assertIn('migrated', migrate_legacy_default('Please find it attached.\r\n\r\nRegards,\r\nTony')) - self.assertEqual(('Please find it attached.\n\nRegards,\nTony\n', 'custom'), load(DEFAULT)) + # the old text had no subject, so it gets the shipped default's, and the old text stays the body + self.assertEqual(('Document attached\n\nPlease find it attached.\n\nRegards,\nTony\n', 'custom'), load(DEFAULT)) + self.assertEqual(('Document attached', 'Please find it attached.\n\nRegards,\nTony\n'), tuple(render_message(load(DEFAULT)[0], build_context({}, 'x'), DEFAULT))) # a user who reverts to the shipped text does not get the old text back at the next start revert(DEFAULT) self.assertIsNone(migrate_legacy_default('Please find it attached.')) @@ -429,6 +451,26 @@ def test_comments_are_never_evaluated(self): # ...but <% is refused everywhere, comment or not self.assertTrue(validate('## <% x %>')) + def test_split_subject(self): + self.assertEqual(('Hello', 'Body\n'), tuple(split_subject('Hello\nBody\n'))) + self.assertEqual(('Hello', 'Body\nmore\n'), tuple(split_subject('Hello\n\n\n \nBody\nmore\n\n\n'))) # separator lines are not the body + self.assertEqual(('Hello', 'Para 1\n\nPara 2\n'), tuple(split_subject('Hello\n\nPara 1\n\nPara 2\n'))) # blank lines inside the body stay + self.assertEqual(('Only a subject', ''), tuple(split_subject('Only a subject\n'))) + self.assertEqual(('Only a subject', ''), tuple(split_subject('Only a subject\n\n \n'))) + self.assertEqual(('', 'Body\n'), tuple(split_subject('\nBody\n'))) # an empty first line: no subject + self.assertEqual(('Trim me', 'x\n'), tuple(split_subject(' Trim me \t\nx\n'))) + self.assertEqual(('', ''), tuple(split_subject(''))) + + def test_the_subject_is_the_first_rendered_line_so_it_can_be_computed(self): + job = self.job() + ctx = build_context(job, 'HAR108', names=['Ann'], company={'name': 'ABFW'}) + text = '## a comment before the subject is not output\n% if doc.tot_due:\nInvoice ${doc.ourref}, \xa3${doc.tot_due}\n% else:\nInvoice ${doc.ourref}\n% endif\n\nHi ${email.name}\n' + self.assertEqual(('Invoice 289099, \xa310.00', 'Hi Ann\n'), tuple(render_message(text, ctx))) + ctx = build_context({'templ': 'invoice', 'parsed': {'A': [{'doc_num': '1', 'ourref': '77', 'accno': 'A', 'tot_due': ''}]}}, 'A') + self.assertEqual('Invoice 77', render_message(text, ctx).subject) + # a template whose first line is blank has no subject, and nothing else moves up into its place + self.assertEqual(('', 'Hi\n'), tuple(render_message('\nHi\n', ctx))) + def test_validate_reports_unbalanced_blocks(self): self.assertTrue(validate('% if doc.a:\nx\n')) @@ -463,8 +505,9 @@ def test_a_broken_custom_template_falls_back_to_the_shipped_one(self): os.makedirs(USER_DIR) with open(user_path('invoice'), 'w') as f: f.write('${__import__("os")}') # written to disk behind the editor's back - body, kind, warning = render_for_job(self.job(), 'HAR108', ['Ann']) - self.assertTrue(body.startswith('To Ann\n\nPlease find your latest invoice')) + message, kind, warning = render_for_job(self.job(), 'HAR108', ['Ann']) + self.assertTrue(message.body.startswith('To Ann\n\nPlease find your latest invoice')) + self.assertTrue(message.subject.startswith('Invoice 289099')) self.assertIn('could not be used', warning) finally: import shutil diff --git a/main.py b/main.py index 1af49fd..817985d 100755 --- a/main.py +++ b/main.py @@ -346,7 +346,7 @@ def settings_templates(query_string='', postreq=None, resp=None): # (for the default template: the newest other document, or the job name / document type that matches) found = emailtemplates.find_document(jobs, kind, term) is_default = kind == emailtemplates.DEFAULT - preview, preview_job, preview_acc, fields, names = None, None, None, [], [] + preview, preview_subject, preview_job, preview_acc, fields, names = None, None, None, None, [], [] if not found: what = 'document' if is_default else '%s document' % emailtemplates.KINDS[kind].lower() preview_note = 'No %s found%s.' % (what, (' matching "%s"' % term) if term else '') @@ -358,27 +358,28 @@ def settings_templates(query_string='', postreq=None, resp=None): fields = emailtemplates.field_names(ctx['doc']) if 'doc' in ctx else [] preview_note = None try: - preview = emailtemplates.render(text, ctx, kind) + rendered = emailtemplates.render_message(text, ctx, kind) + preview, preview_subject = rendered.body, rendered.subject except emailtemplates.TemplateError as e: errors = errors or e.errors return ( template_lookup.get_template("/settings_templates.html").render( kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, user_path=emailtemplates.user_path(kind), - term=term, message=message, errors=errors, preview=preview, preview_note=preview_note, + term=term, message=message, errors=errors, preview=preview, preview_subject=preview_subject, preview_note=preview_note, preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, is_default=is_default), 'text/html') def email_body(query_string=dict(), resp=None): """The suggested email text for a document if only the contacts whose addresses are in 'em' are recipients. The compose form asks for this when contacts are ticked or unticked, since a template can use - the recipients' names. No 'em' means no recipients. Answers {"body": ..., "warning": ...}.""" + the recipients' names. No 'em' means no recipients. Answers {"subject": ..., "body": ..., "warning": ...}.""" job = getJob(query_string) default_key = next(iter(job.get('groupfiles') or {}), ('',))[0] key = query_string.get('key', [default_key])[0] known = email_addresses.get(key, {}) ticked = query_string.get('em', []) - body, kind, warning = emailtemplates.render_for_job( + message, kind, warning = emailtemplates.render_for_job( job, key, names=[known[a] for a in ticked if a in known], addresses=ticked, company=company_info()) - return json.dumps({'body': body, 'warning': warning}), 'text/json' + return json.dumps({'subject': message.subject, 'body': message.body, 'warning': warning}), 'text/json' def pdf(query_string=dict(), resp=None): job = getJob(query_string) @@ -411,11 +412,13 @@ def pdf(query_string=dict(), resp=None): except: raise - # the suggested body comes from the template for this type of document (or the default template) - email_body_default, template_kind, template_warning, template_docnum = '', emailtemplates.DEFAULT, None, '' + # the suggested subject and body come from the template for this type of document (or the default template) + email_subject_default, email_body_default = '', '' + template_kind, template_warning, template_docnum = emailtemplates.DEFAULT, None, '' try: - email_body_default, template_kind, template_warning = emailtemplates.render_for_job( + message, template_kind, template_warning = emailtemplates.render_for_job( job, key, names=list(email_dest.values()), addresses=list(email_dest.keys()), company=company_info()) + email_subject_default, email_body_default = message.subject, message.body except Exception: traceback.print_exc(file=sys.stdout) template_warning = 'The email template for this document could not be used.' @@ -427,7 +430,7 @@ def pdf(query_string=dict(), resp=None): pages = parsed.get(emailtemplates.account_for_key(parsed, key)) or [{}] template_docnum = pages[0].get('doc_num', '').strip() - return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, + return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') diff --git a/templates/default.mako b/templates/default.mako index 6835f14..163ef6e 100644 --- a/templates/default.mako +++ b/templates/default.mako @@ -1,3 +1,5 @@ +Document attached + To ${email.name} Please find your document attached. diff --git a/templates/invoice.mako b/templates/invoice.mako index 1f09c5e..59115eb 100644 --- a/templates/invoice.mako +++ b/templates/invoice.mako @@ -1,3 +1,5 @@ +Invoice ${doc.ourref} from ${company.name} + To ${email.name} Please find your latest invoice ${doc.ourref} attached for account ${doc.accno}, for £${doc.tot_due}. diff --git a/templates/purchase.mako b/templates/purchase.mako index b02cb9f..5ce4058 100644 --- a/templates/purchase.mako +++ b/templates/purchase.mako @@ -1,3 +1,5 @@ +Purchase order ${doc.doc_num} from ${company.name} + To ${email.name} Please find attached purchase order ${doc.doc_num}, dated ${doc.orderdate}, for account ${doc.accno}. diff --git a/templates/statement.mako b/templates/statement.mako index b446c74..3fce72a 100644 --- a/templates/statement.mako +++ b/templates/statement.mako @@ -1,3 +1,5 @@ +Statement dated ${doc.date} from ${company.name} + To ${email.name} Please find attached your statement dated ${doc.date} for account ${doc.accno}. diff --git a/test_compose.js b/test_compose.js index 235daa8..f4d9311 100644 --- a/test_compose.js +++ b/test_compose.js @@ -12,80 +12,117 @@ function element(props) { }, props); } -function setup(addresses, text, url = '/email_body?name=job-1&key=ACC1') { +// options.subject: initial subject text, or null for a page without a subject box +function setup(addresses, text, options = {}) { + const url = 'url' in options ? options.url : '/email_body?name=job-1&key=ACC1'; const boxes = addresses.map(a => element({name: 'em', value: a, checked: true})); const area = element({value: text, attrs: url ? {'data-url': url} : {}}); + const subject = 'subject' in options && options.subject === null ? undefined : element({value: options.subject || ''}); const notice = element({style: {display: 'none'}}); const reapply = element({}); - const byId = {inputBody: area, bodyNotice: notice, bodyReapply: reapply}; + const byId = {inputBody: area, inputSubject: subject, bodyNotice: notice, bodyReapply: reapply}; const doc = {getElementById: id => byId[id], querySelectorAll: () => boxes}; const requests = []; - const fetchFn = u => new Promise(resolve => requests.push({url: u, answer: body => resolve({json: () => Promise.resolve({body})})})); - return {boxes, area, notice, reapply, requests, api: init(doc, fetchFn)}; + // answer({subject, body}) or answer('body only') + const fetchFn = u => new Promise(resolve => requests.push({ + url: u, + answer: a => resolve({json: () => Promise.resolve(typeof a === 'string' ? {body: a} : a)}), + })); + return {boxes, area, subject, notice, reapply, requests, api: init(doc, fetchFn)}; } const settle = () => new Promise(resolve => setImmediate(resolve)); +const untick = (t, i) => { t.boxes[i].checked = false; t.boxes[i].fire('change'); }; (async () => { // ticking and unticking asks the server with exactly the ticked addresses, in page order, and uses the answer - let t = setup(['ann@x.com', 'bob+co@x.com'], 'To Ann and Bob\n'); - t.boxes[0].checked = false; - t.boxes[0].fire('change'); + let t = setup(['ann@x.com', 'bob+co@x.com'], 'To Ann and Bob\n', {subject: 'Invoice 1'}); + untick(t, 0); assert.strictEqual(t.requests.length, 1); assert.strictEqual(t.requests[0].url, '/email_body?name=job-1&key=ACC1&em=bob%2Bco%40x.com'); - t.requests[0].answer('To Bob\n'); + t.requests[0].answer({subject: 'Invoice 1 for Bob', body: 'To Bob\n'}); await settle(); assert.strictEqual(t.area.value, 'To Bob\n'); + assert.strictEqual(t.subject.value, 'Invoice 1 for Bob'); assert.strictEqual(t.notice.style.display, 'none'); // nothing ticked: no em at all - t.boxes[1].checked = false; - t.boxes[1].fire('change'); + untick(t, 1); assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1'); - t.requests[1].answer('To Sir or Madam\n'); + t.requests[1].answer({subject: 'Invoice 1', body: 'To Sir or Madam\n'}); await settle(); assert.strictEqual(t.area.value, 'To Sir or Madam\n'); + assert.strictEqual(t.subject.value, 'Invoice 1'); - // edited text is kept, with a notice; the link replaces it using the current ticks - t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); + // an edited body is kept, with a notice, while the untouched subject still follows the recipients + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'For Ann and Bob'}); t.area.value = 'To Ann and Bob\nmy own words\n'; - t.boxes[1].checked = false; - t.boxes[1].fire('change'); - t.requests[0].answer('To Ann\n'); + untick(t, 1); + t.requests[0].answer({subject: 'For Ann', body: 'To Ann\n'}); await settle(); assert.strictEqual(t.area.value, 'To Ann and Bob\nmy own words\n'); + assert.strictEqual(t.subject.value, 'For Ann'); assert.strictEqual(t.notice.style.display, ''); + + // the link replaces everything using the current ticks t.reapply.fire('click'); assert.strictEqual(t.requests[1].url, '/email_body?name=job-1&key=ACC1&em=ann%40x.com'); - t.requests[1].answer('To Ann\n'); + t.requests[1].answer({subject: 'For Ann', body: 'To Ann\n'}); await settle(); assert.strictEqual(t.area.value, 'To Ann\n'); assert.strictEqual(t.notice.style.display, 'none'); + // an edited subject is kept while the body follows; and both edited means both kept + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'For Ann and Bob'}); + t.subject.value = 'My own subject'; + untick(t, 1); + t.requests[0].answer({subject: 'For Ann', body: 'To Ann\n'}); + await settle(); + assert.strictEqual(t.subject.value, 'My own subject'); + assert.strictEqual(t.area.value, 'To Ann\n'); + assert.strictEqual(t.notice.style.display, ''); + t.area.value = 'typed'; + t.boxes[1].checked = true; t.boxes[1].fire('change'); + t.requests[1].answer({subject: 'For Ann and Bob', body: 'To Ann and Bob\n'}); + await settle(); + assert.deepStrictEqual([t.subject.value, t.area.value], ['My own subject', 'typed']); + t.reapply.fire('click'); + t.requests[2].answer({subject: 'For Ann and Bob', body: 'To Ann and Bob\n'}); + await settle(); + assert.deepStrictEqual([t.subject.value, t.area.value, t.notice.style.display], ['For Ann and Bob', 'To Ann and Bob\n', 'none']); + // text that was refreshed by us is not "edited": a second tick updates it again without a notice - t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); - t.boxes[0].checked = false; t.boxes[0].fire('change'); t.requests[0].answer('To Bob\n'); await settle(); - t.boxes[0].checked = true; t.boxes[0].fire('change'); t.requests[1].answer('To Ann and Bob\n'); await settle(); - assert.strictEqual(t.area.value, 'To Ann and Bob\n'); - assert.strictEqual(t.notice.style.display, 'none'); + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'S1'}); + untick(t, 0); t.requests[0].answer({subject: 'S2', body: 'To Bob\n'}); await settle(); + t.boxes[0].checked = true; t.boxes[0].fire('change'); t.requests[1].answer({subject: 'S1', body: 'To Ann and Bob\n'}); await settle(); + assert.deepStrictEqual([t.subject.value, t.area.value, t.notice.style.display], ['S1', 'To Ann and Bob\n', 'none']); // answers arriving out of order: only the answer to the latest tick is used - t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n'); - t.boxes[0].checked = false; t.boxes[0].fire('change'); - t.boxes[1].checked = false; t.boxes[1].fire('change'); - t.requests[1].answer('To Sir or Madam\n'); + t = setup(['ann@x.com', 'bob@x.com'], 'To Ann and Bob\n', {subject: 'S1'}); + untick(t, 0); untick(t, 1); + t.requests[1].answer({subject: 'Latest', body: 'To Sir or Madam\n'}); await settle(); - t.requests[0].answer('To Bob\n'); + t.requests[0].answer({subject: 'Stale', body: 'To Bob\n'}); await settle(); + assert.deepStrictEqual([t.subject.value, t.area.value], ['Latest', 'To Sir or Madam\n']); + + // a page with no subject box still updates the body + t = setup(['ann@x.com'], 'To Ann\n', {subject: null}); + untick(t, 0); t.requests[0].answer({subject: 'x', body: 'To Sir or Madam\n'}); await settle(); assert.strictEqual(t.area.value, 'To Sir or Madam\n'); + // an answer missing a field leaves that box as it was (never the text 'undefined') + t = setup(['ann@x.com'], 'To Ann\n', {subject: 'Keep me'}); + untick(t, 0); t.requests[0].answer('To Sir or Madam\n'); await settle(); + assert.deepStrictEqual([t.subject.value, t.area.value], ['Keep me', 'To Sir or Madam\n']); + // a failed request leaves the text alone - t = setup(['ann@x.com'], 'To Ann\n'); - const failing = {getElementById: id => ({inputBody: t.area}[id]), querySelectorAll: () => t.boxes}; + t = setup(['ann@x.com'], 'To Ann\n', {subject: 'S'}); + const failing = {getElementById: id => ({inputBody: t.area, inputSubject: t.subject}[id]), querySelectorAll: () => t.boxes}; const api = init(failing, () => Promise.reject(new Error('offline'))); await api.refresh(false); - assert.strictEqual(t.area.value, 'To Ann\n'); + assert.deepStrictEqual([t.subject.value, t.area.value], ['S', 'To Ann\n']); // a page without the compose form is left alone - assert.strictEqual(setup(['a@x.com'], 'x', null).api, undefined); + assert.strictEqual(setup(['a@x.com'], 'x', {url: null}).api, undefined); console.log('compose.js: all tests passed'); })().catch(e => { console.error(e); process.exit(1); }); diff --git a/test_integration.py b/test_integration.py index 39e75f2..9faf641 100644 --- a/test_integration.py +++ b/test_integration.py @@ -248,6 +248,7 @@ def test_recent_json_ts_is_per_job(self): self.assertEqual(first['ts'].isoformat(), rows[first['name']]['ts']) self.assertEqual(second['ts'].isoformat(), rows[second['name']]['ts']) + INVOICE_SUBJECT = 'Invoice 289073 from YOUR DOMAIN LTD.' INVOICE_TEXT = 'To %s\n\nPlease find your latest invoice 289073 attached for account ACC001, for \xa3123.45.' def test_compose_form_is_prefilled_from_the_invoice_template(self): @@ -256,6 +257,8 @@ def test_compose_form_is_prefilled_from_the_invoice_template(self): self.assertEqual(200, r.status) self.assertNotIn(b'Mako Runtime Error', body) self.assertIn((self.INVOICE_TEXT % 'Sir or Madam').encode('utf-8'), body) + self.assertIn(('name="subject" placeholder="Subject" value="%s"' % self.INVOICE_SUBJECT).encode(), body) + self.assertNotIn(self.INVOICE_SUBJECT.encode() + b'\n', body) # the subject is not repeated in the text self.assertIn(b'/settings/templates?kind=invoice&docnum=12345', body) # with contacts on the account the greeting names them, and html in a name is escaped in the textarea self.get('/settings/email?account=ACC001&email=a%40example.com&contact=Ann') @@ -263,6 +266,7 @@ def test_compose_form_is_prefilled_from_the_invoice_template(self): r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertIn((self.INVOICE_TEXT % 'Ann and Bob & Co').encode('utf-8'), body) + DEFAULT_SUBJECT = 'Document attached' DEFAULT_TEXT = 'To %s\n\nPlease find your document attached.' def test_other_documents_use_the_default_template(self): @@ -272,6 +276,7 @@ def test_other_documents_use_the_default_template(self): self.assertEqual(200, r.status) self.assertNotIn(b'Mako Runtime Error', body) self.assertIn((self.DEFAULT_TEXT % 'Sir or Madam').encode('utf-8'), body) + self.assertIn(('value="%s"' % self.DEFAULT_SUBJECT).encode(), body) self.assertIn(('/settings/templates?kind=default&docnum=' + j['name']).encode(), body) self.assertIn(b'Edit the default email template', body) @@ -299,10 +304,15 @@ def test_template_editor_preview_save_and_revert(self): # preview renders what is typed without saving it r, body = self.post('/settings/templates', kind='invoice', action='preview', docnum='424242', - template='Hi ${email.name}, invoice ${doc.doc_num} for \xa3${doc.tot_due}.') + template='Re ${doc.doc_num}\n\nHi ${email.name}, invoice ${doc.doc_num} for \xa3${doc.tot_due}.') self.assertEqual(200, r.status) + self.assertIn(b'Subject: Re 424242', body) self.assertIn('Hi Sir or Madam, invoice 424242 for \xa3123.45.'.encode('utf-8'), body) self.assertFalse(os.path.exists(path)) + # a first line that renders empty means no subject, and the editor says so + r, body = self.post('/settings/templates', kind='invoice', action='preview', docnum='424242', template='\nJust text') + self.assertIn(b'the first line of the template is empty', body) + self.assertIn(b'Just text', body) # save writes the user template, and the compose form then uses it r, body = self.post('/settings/templates', kind='invoice', action='save', docnum='', @@ -312,14 +322,17 @@ def test_template_editor_preview_save_and_revert(self): with open(path, encoding='utf-8') as f: self.assertEqual('Dear ${email.name}\nInvoice ${doc.doc_num}\n', f.read()) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) - self.assertIn(b'Dear Sir or Madam\nInvoice 424242', body) + self.assertIn(b'value="Dear Sir or Madam"', body) # the first line is the subject... + self.assertIn(b'Invoice 424242', body) # ...and the rest is the text + self.assertNotIn(b'Dear Sir or Madam\nInvoice', body) # revert goes back to the shipped text r, body = self.post('/settings/templates', kind='invoice', action='revert') self.assertIn(b'Reverted to the shipped invoice template', body) self.assertFalse(os.path.exists(path)) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) - self.assertIn((self.INVOICE_TEXT.replace('289073', '289073') % 'Sir or Madam').encode('utf-8'), body) + self.assertIn((self.INVOICE_TEXT % 'Sir or Madam').encode('utf-8'), body) + self.assertIn(('value="%s"' % self.INVOICE_SUBJECT).encode(), body) def test_template_editor_refuses_templates_that_could_run_code(self): self.send_invoice() @@ -360,9 +373,14 @@ def body(*ticked): self.assertTrue(body('bob@x.com').startswith('To Bob\n\nPlease find')) self.assertTrue(body().startswith('To Sir or Madam\n\nPlease find')) # nobody ticked self.assertTrue(body('stranger@x.com').startswith('To Sir or Madam\n')) # not in the address book: no name to use - self.post('/settings/templates', kind='invoice', action='save', template='${email.name} <${email.address}>') - self.assertEqual('Bob and Ann \n', body('bob@x.com', 'ann@x.com')) # the first ticked address - self.assertEqual('Sir or Madam <>\n', body()) + query = 'name=%s&key=ACC001&em=bob%%40x.com&em=ann%%40x.com' % j['name'] + self.assertEqual(self.INVOICE_SUBJECT, json.loads(self.get('/email_body?' + query)[1].decode())['subject']) + # subject and body both follow the recipients: first line is the subject, the rest the body + self.post('/settings/templates', kind='invoice', action='save', template='For ${email.name}\n\n${email.name} <${email.address}>') + answer = json.loads(self.get('/email_body?' + query)[1].decode()) + self.assertEqual(('For Bob and Ann', 'Bob and Ann \n'), (answer['subject'], answer['body'])) # the first ticked address + answer = json.loads(self.get('/email_body?name=%s&key=ACC001' % j['name'])[1].decode()) + self.assertEqual(('For Sir or Madam', 'Sir or Madam <>\n'), (answer['subject'], answer['body'])) def test_compose_form_is_wired_for_live_updates(self): j = self.send_invoice() @@ -427,8 +445,9 @@ def test_the_old_single_email_text_is_migrated_once_at_startup(self): main.jobs.clear(); main.recover() r, body = self.get('/pdf?name=' + j['name']) self.assertIn(b'Please find it attached.\n\nRegards,\nTony Page', body) + self.assertIn(('value="%s"' % self.DEFAULT_SUBJECT).encode(), body) with open(emailtemplates.user_path('default'), encoding='utf-8') as f: - self.assertEqual('Please find it attached.\n\nRegards,\nTony Page\n', f.read()) + self.assertEqual('Document attached\n\nPlease find it attached.\n\nRegards,\nTony Page\n', f.read()) # reverting is not undone by the next restart self.post('/settings/templates', kind='default', action='revert') with contextlib.redirect_stdout(io.StringIO()): diff --git a/web/js/compose.js b/web/js/compose.js index bc5f4b6..018c5e1 100644 --- a/web/js/compose.js +++ b/web/js/compose.js @@ -1,6 +1,6 @@ -// Email compose form: when a contact is ticked or unticked the suggested text is re-rendered by the server, -// since the template can use the recipients (${email.name}). Text the user has already edited is never -// replaced silently: it is kept, and a notice offers to replace it. +// Email compose form: when a contact is ticked or unticked the suggested subject and text are re-rendered by +// the server, since the template can use the recipients (${email.name}). A field the user has already edited +// is never replaced silently: it is kept, and a notice offers to replace it. (function () { function init(doc, fetchFn) { var area = doc.getElementById('inputBody'); @@ -10,8 +10,14 @@ var boxes = doc.querySelectorAll('input[name="em"]'); var notice = doc.getElementById('bodyNotice'); var reapply = doc.getElementById('bodyReapply'); - var lastRendered = area.value; // what the server gave us; anything else in the box was typed var latest = 0; + // 'last' is what the server gave us; anything else in the box was typed + var fields = [{el: doc.getElementById('inputSubject'), key: 'subject'}, {el: area, key: 'body'}].filter(function (f) { + return f.el; + }); + fields.forEach(function (f) { + f.last = f.el.value; + }); function selected() { var out = []; @@ -45,13 +51,19 @@ if (mine !== latest) { return; // a later tick has asked again; its answer is the one that counts } - if (area.value !== lastRendered && !replaceEdits) { - showNotice(true); - return; - } - area.value = d.body; - lastRendered = area.value; - showNotice(false); + var kept = false; + fields.forEach(function (f) { + if (typeof d[f.key] !== 'string') { + return; // never put 'undefined' in a box if an answer lacks a field + } + if (f.el.value !== f.last && !replaceEdits) { + kept = true; + return; + } + f.el.value = d[f.key]; + f.last = f.el.value; + }); + showNotice(kept); }).catch(function () { // leave the text as it is; the user can still edit it by hand }); diff --git a/web/pdf.html b/web/pdf.html index 5bca09f..32059a1 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -85,8 +85,8 @@

    Compose Email

    - -
    + +
    @@ -99,7 +99,7 @@

    Compose Email

    ${email_templ | h} % if template_warning: diff --git a/web/settings_templates.html b/web/settings_templates.html index 642907d..d026537 100644 --- a/web/settings_templates.html +++ b/web/settings_templates.html @@ -3,7 +3,8 @@

    Email Templates

    The text offered when you email a document. Invoices, purchase orders and statements have a template each; -every other document (delivery notes, credit notes, reports…) uses the Default one.

    +every other document (delivery notes, credit notes, reports…) uses the Default one. +The first line of a template is the email's subject; the rest is the text of the email.

    % if is_default: - Only plain text, ${'${email.name}'}, ${'${job.name}'}, % if job.host: and ## comments are allowed. + Only plain text, ${'${email.name}'}, ${'${job.name}'}, ${'${company.name}'}, % if job.host: and ## comments are allowed. % else: Only plain text, ${'${doc.field}'}, % for d in docs:, % if doc.field: and ## comments are allowed. % endif @@ -99,9 +99,7 @@

    Available fields

    ${'${email.name}'} ${'${email.address}'} ${'${job.name}'} ${'${job.doctype}'} ${'${job.host}'} - % if not is_default: ${'${company.name}'} ${'${company.email}'} ${'${company.website}'} - % endif

    % if fields:

    From this document: @@ -113,8 +111,8 @@

    Available fields

    % endif % if is_default: -

    The default template is used for documents whose contents printerface doesn't read, so only the recipients -and the job are available. Add | trim to remove surrounding spaces.

    +

    The default template is used for documents whose contents printerface doesn't read, so only the recipients, +the job and the company details are available. Add | trim to remove surrounding spaces.

    % else:

    If an account has several documents in one print run, doc is the last of them; use % for d in docs: … % endfor with ${'${d.field}'} to visit each one. From 5de667cab49f552dca11c9030253ff88504e597d Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 13:12:53 +0000 Subject: [PATCH 18/31] Template editor: show just 'Template ' above the text The line no longer says whether the template is customised or what saving will write; the Revert button still only appears for a customised template. Co-Authored-By: Claude Sonnet 5.5 --- main.py | 2 +- test_integration.py | 6 ++++-- web/settings_templates.html | 8 +------- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index 817985d..68c093b 100755 --- a/main.py +++ b/main.py @@ -364,7 +364,7 @@ def settings_templates(query_string='', postreq=None, resp=None): errors = errors or e.errors return ( template_lookup.get_template("/settings_templates.html").render( - kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, user_path=emailtemplates.user_path(kind), + kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, filename=os.path.basename(emailtemplates.user_path(kind)), term=term, message=message, errors=errors, preview=preview, preview_subject=preview_subject, preview_note=preview_note, preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, is_default=is_default), 'text/html') diff --git a/test_integration.py b/test_integration.py index a059bb7..26ce599 100644 --- a/test_integration.py +++ b/test_integration.py @@ -296,7 +296,8 @@ def test_template_editor_preview_save_and_revert(self): r, body = self.get('/settings/templates?kind=invoice') self.assertEqual(200, r.status) self.assertNotIn(b'Mako Runtime Error', body) - self.assertIn(b'default template shipped with printerface', body) + self.assertIn(b'

    Template invoice.mako

    ', body) + self.assertNotIn(b'Revert to default', body) # nothing customised yet, so nothing to revert self.assertIn(b'Please find your latest invoice 289073 attached', body) # preview of the newest invoice for kind in ('purchase', 'statement'): r, body = self.get('/settings/templates?kind=' + kind) @@ -327,7 +328,8 @@ def test_template_editor_preview_save_and_revert(self): r, body = self.post('/settings/templates', kind='invoice', action='save', docnum='', template='Dear ${email.name}\r\nInvoice ${doc.doc_num}\r\n') self.assertIn(b'Saved the invoice template', body) - self.assertIn(b'Using your customised template', body) + self.assertIn(b'

    Template invoice.mako

    ', body) # the same line, customised or not + self.assertIn(b'Revert to default', body) with open(path, encoding='utf-8') as f: self.assertEqual('Dear ${email.name}\nInvoice ${doc.doc_num}\n', f.read()) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) diff --git a/web/settings_templates.html b/web/settings_templates.html index 6520c80..db9c022 100644 --- a/web/settings_templates.html +++ b/web/settings_templates.html @@ -40,13 +40,7 @@

    Email Templates

    -

    - % if source == 'custom': - Using your customised template, saved as ${user_path | h}. - % else: - Using the default template shipped with printerface. Saving creates ${user_path | h}. - % endif -

    +

    Template ${filename | h}

    From ce71c2412946ec37da523b06c36ef564adda4835 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 13:24:28 +0000 Subject: [PATCH 19/31] Sent Items: show only the latest 100 emails The history goes back years (about 41,000 emails in production's) and rendering all of it makes a page of several MB. The page now shows the newest 100 and says how many there are in total; the history itself is untouched. Co-Authored-By: Claude Sonnet 5.5 --- main.py | 7 ++++++- test_integration.py | 27 +++++++++++++++++++++++++++ web/sent.html | 6 +++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 68c093b..83aa582 100755 --- a/main.py +++ b/main.py @@ -267,8 +267,13 @@ def job(query_string=dict(), resp=None): def printers(query_string='', resp=None): return ( template_lookup.get_template("/printers.html").render(printers=getPrinters()), 'text/html') +# The Sent Items page only shows this many of the most recent emails, however long the history is: the +# history goes back years and the whole of it makes a page of many MB. +SENT_SHOWN = 100 + def sent(query_string='', resp=None): - return ( template_lookup.get_template("/sent.html").render(mailqueue=mailqueue), 'text/html') + results = mailqueue.results # newest first; the mail thread inserts at the front + return ( template_lookup.get_template("/sent.html").render(shown=results[:SENT_SHOWN], total=len(results)), 'text/html') def settings_email(query_string='', postreq=None, resp=None): warning=None diff --git a/test_integration.py b/test_integration.py index 26ce599..c27458b 100644 --- a/test_integration.py +++ b/test_integration.py @@ -64,6 +64,9 @@ def ack(): finally: s.close() +def mailer_results(): + return main.mailqueue.results + class ServerThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) @@ -480,6 +483,30 @@ def test_the_old_default_text_editor_is_gone(self): self.assertNotIn(b'Default Email Text', body) self.assertIn(b'/settings/templates', body) + def test_sent_items_shows_only_the_latest_100(self): + import datetime + def fake(i): + now = datetime.datetime(2026, 11, 19, 12, 0, 0) + return dict(to=['a%d@x.com' % i], subject='subject-%d' % i, added=now, completed=now, error=None, status=None, body='', attachment='') + original = list(mailer_results()) + try: + mailer_results()[:] = [fake(i) for i in range(250)] # newest first, as the mail thread keeps it + r, body = self.get('/sent') + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertEqual(100, len(re.findall(rb'', body))) + self.assertIn(b'subject-0<', body) + self.assertIn(b'subject-99<', body) + self.assertNotIn(b'subject-100<', body) + self.assertIn(b'Showing the latest 100 of 250 sent emails.', body) + # a history that fits is shown whole, with no note + mailer_results()[:] = [fake(i) for i in range(3)] + r, body = self.get('/sent') + self.assertEqual(3, len(re.findall(rb'', body))) + self.assertNotIn(b'Showing the latest', body) + finally: + mailer_results()[:] = original + def test_keepalive_two_requests_one_connection(self): self.send_invoice() conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) diff --git a/web/sent.html b/web/sent.html index 64f80cf..279d813 100644 --- a/web/sent.html +++ b/web/sent.html @@ -4,9 +4,13 @@

    Sent Items

    + % if total > len(shown): +

    Showing the latest ${len(shown)} of ${total} sent emails.

    + % endif + - % for p in mailqueue.results: + % for p in shown: % if p['error']: % else: From 08892f42be9864d9356a284725915001b722dc53 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 13:46:12 +0000 Subject: [PATCH 20/31] Link sent items to their job, and list a job's sent emails on its page A sent item's attachment path names the job and document it was made from (job-YYYYMMDD-HHMMSS-.pdf), so every existing record can be linked without changing the data. Sent Items gets a Document column that links to the job page when the job is still loaded and just names it otherwise. The job page lists the emails sent from it, newest first. /pdf for a job that isn't loaded (a stale link, or after a restart) now says so, with the name escaped, instead of failing with a 500. Co-Authored-By: Claude Sonnet 5.5 --- mailer.py | 43 +++++++++++++++++++++++++++++++- main.py | 21 ++++++++++++++-- test_integration.py | 61 +++++++++++++++++++++++++++++++++++++++++++++ web/pdf.html | 16 ++++++++++++ web/sent.html | 20 +++++++++++---- 5 files changed, 153 insertions(+), 8 deletions(-) diff --git a/mailer.py b/mailer.py index e52c181..bcdd8c4 100644 --- a/mailer.py +++ b/mailer.py @@ -13,13 +13,34 @@ # http://stackoverflow.com/questions/3362600/how-to-send-email-attachments-with-python import datetime -import os, threading +import os, re, threading import queue import traceback import pickle pickle_file = os.path.join(HOME, 'mailer.pickle') +# An emailed PDF is stored as ///-.pdf (or /raw//-.pdf), so +# the attachment path of a sent item says which job and which of its documents it came from. is the name +# the job page knows the document by (an account, 'accounts', 'plain', ...) and is job-YYYYMMDD-HHMMSS. +_job_ref = re.compile(r'(job-\d{8}-\d{6})-(.+)\.pdf$') + +def job_ref(attachment): + """(job name, key) for the attachment path of a sent item, or None if it isn't one of ours.""" + m = _job_ref.search(attachment or '') + return (m.group(1), m.group(2)) if m else None + +def sent_from_job(results, job_name): + """The sent items made from this job, newest first, each with its job key. results is newest first.""" + prefix = job_name + '-' + out = [] + for r in list(results): + if prefix in (r.get('attachment') or ''): + ref = job_ref(r['attachment']) + if ref and ref[0] == job_name: + out.append((r, ref[1])) + return out + class JobMailer(object): def __init__(self, queuesz=10): @@ -118,6 +139,26 @@ def sendJobAttachment(self, text, file, filename, subject="sending with gmail", s.set_debuglevel(2) s.close() +import unittest + +class TestSentItemLinks(unittest.TestCase): + def test_job_ref(self): + self.assertEqual(('job-20261111-111416', 'HAR108'), job_ref('/home/printerface/printerface/data/pdf/2026/HAR108/job-20261111-111416-HAR108.pdf')) + self.assertEqual(('job-20150715-101010', 'plain'), job_ref('/x/data/pdf/raw/201507/job-20150715-101010-plain.pdf')) + self.assertEqual(('job-20261020-112058', 'AYU100-admin'), job_ref('/x/2026/AYU100/job-20261020-112058-AYU100-admin.pdf')) + self.assertEqual(('job-20261020-112058', 'MULTI-21'), job_ref('/x/2026/MULTI-21/job-20261020-112058-MULTI-21.pdf')) + self.assertEqual(('job-20261020-112058', 'accounts'), job_ref('C:\\\\x\\\\2026\\\\accounts\\\\job-20261020-112058-accounts.pdf')) + for bad in ('', None, '/x/report.pdf', '/x/job-1-2-3.pdf', '/x/job-20261020-112058.pdf', '/x/job-20261020-112058-A.txt'): + self.assertIsNone(job_ref(bad), bad) + + def test_sent_from_job(self): + mk = lambda att, n: {'attachment': att, 'subject': n} + results = [mk('/p/2026/B/job-20261111-111416-B.pdf', 'newest'), mk('/p/2026/A/job-20261111-111416-A.pdf', 'a'), + mk('/p/2026/A/job-20261111-111417-A.pdf', 'other job'), mk('', 'no attachment'), {'subject': 'no key'}] + found = sent_from_job(results, 'job-20261111-111416') + self.assertEqual([('newest', 'B'), ('a', 'A')], [(r['subject'], key) for r, key in found]) + self.assertEqual([], sent_from_job(results, 'job-20000101-000000')) + if __name__=="__main__": import time diff --git a/main.py b/main.py index 83aa582..df93814 100755 --- a/main.py +++ b/main.py @@ -8,12 +8,14 @@ from datetime import datetime from lpdserver import LpdServer from httpserver import ToyHttpServer +import mailer from mailer import JobMailer from docparser import DocParser from stationary import DocFormatter from printing import getPrinters, printFile import sys, pickle +import html import urllib.parse from io import StringIO import collections @@ -273,7 +275,13 @@ def printers(query_string='', resp=None): def sent(query_string='', resp=None): results = mailqueue.results # newest first; the mail thread inserts at the front - return ( template_lookup.get_template("/sent.html").render(shown=results[:SENT_SHOWN], total=len(results)), 'text/html') + loaded = set(j['name'] for j in jobs) + rows = [] + for p in results[:SENT_SHOWN]: + ref = mailer.job_ref(p.get('attachment')) + # only jobs still in memory can be opened; for older ones the name is shown without a link + rows.append(dict(p=p, job=ref[0] if ref else None, key=ref[1] if ref else None, loaded=bool(ref and ref[0] in loaded))) + return ( template_lookup.get_template("/sent.html").render(rows=rows, total=len(results)), 'text/html') def settings_email(query_string='', postreq=None, resp=None): warning=None @@ -388,6 +396,10 @@ def email_body(query_string=dict(), resp=None): def pdf(query_string=dict(), resp=None): job = getJob(query_string) + if not job.get('groupfiles'): + name = query_string.get('name', [''])[0] + return doMessage(title='Job not found', message='There is no job %s loaded. Only the most recent jobs are kept in memory, so older ones ' + 'can\'t be opened here. Recent jobs' % (html.escape(name) or '(none given)')) default_key = next(iter(job['groupfiles']))[0] key = query_string.get('key', [default_key])[0] email_dest = email_addresses.get(key, {}) @@ -427,6 +439,9 @@ def pdf(query_string=dict(), resp=None): except Exception: traceback.print_exc(file=sys.stdout) template_warning = 'The email template for this document could not be used.' + # emails made from this job that are still in the sent history, newest first + sent_from_this_job = mailer.sent_from_job(mailqueue.results, job['name']) + # what the editor's preview filter should be set to so that it shows this document if template_kind == emailtemplates.DEFAULT: template_docnum = job.get('name', '') @@ -436,7 +451,7 @@ def pdf(query_string=dict(), resp=None): template_docnum = pages[0].get('doc_num', '').strip() return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, - template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, + template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') @@ -472,6 +487,8 @@ def getJob(query_string, returnLast=False): def getJobFile(query_string, job=None): if not job: job = getJob(query_string) + if not job.get('groupfiles'): + return None default_key = next(iter(job['groupfiles']))[0] key = query_string.get('key', [default_key])[0] diff --git a/test_integration.py b/test_integration.py index c27458b..d41c391 100644 --- a/test_integration.py +++ b/test_integration.py @@ -507,6 +507,67 @@ def fake(i): finally: mailer_results()[:] = original + def fake_sent(self, attachment, subject, to=('a@x.com',), error=None): + import datetime + now = datetime.datetime(2026, 11, 19, 12, 0, 0) + return dict(to=list(to), subject=subject, added=now, completed=now, error=error, status=None, body='', attachment=attachment) + + def test_sent_items_link_to_the_job_and_the_job_lists_them(self): + j = self.send_invoice(doc_num='777') + other = self.send_invoice(doc_num='888') + name = j['name'] + made_here = main.pdfdir + '2026/ACC001/%s-ACC001.pdf' % name + long_gone = '/home/printerface/printerface/data/pdf/2015/OLD001/job-20150715-101010-OLD001.pdf' + original = list(mailer_results()) + try: + mailer_results()[:] = [ # newest first + self.fake_sent(long_gone, 'sent long ago'), + self.fake_sent(made_here, 'second mail', to=['ann@x.com', 'bob@x.com'], error='boom '), + self.fake_sent(made_here, 'first mail'), + self.fake_sent('', 'no attachment'), + ] + r, body = self.get('/sent') + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertEqual(2, body.count(('href="/pdf?name=%s&key=ACC001"' % name).encode())) # one link per email from the loaded job + self.assertIn(b'job-20150715-101010', body) # the old job is named... + self.assertNotIn(b'name=job-20150715-101010', body) # ...but not linked + + # the job page lists the emails made from it, and only those + r, body = self.get('/pdf?name=%s&key=ACC001' % name) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertIn(b'

    Sent from this job

    ', body) + self.assertIn(b'first mail', body) + self.assertIn(b'second mail', body) + self.assertLess(body.index(b'second mail'), body.index(b'first mail')) # newest first + self.assertIn(b'ann@x.com, bob@x.com', body) + self.assertIn(b'boom <b>', body) # escaped + self.assertNotIn(b'sent long ago', body) + # a job nothing was sent from has no such section + r, body = self.get('/pdf?name=%s&key=ACC001' % other['name']) + self.assertNotIn(b'Sent from this job', body) + finally: + mailer_results()[:] = original + + def test_pdf_page_for_a_job_that_is_not_loaded_is_a_message_not_an_error(self): + self.send_invoice() + r, body = self.get('/pdf?name=job-19990101-000000') + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertNotIn(b'Traceback', body) + self.assertIn(b'There is no job job-19990101-000000 loaded', body) + self.assertIn(b'href="/recent"', body) + r, body = self.get('/pdf?name=%3Cb%3Ex%3C/b%3E') # the name is echoed back, escaped + self.assertEqual(200, r.status) + self.assertIn(b'<b>x</b>', body) + self.assertNotIn(b'x', body) + r, body = self.get('/pdf') + self.assertEqual(200, r.status) + self.assertIn(b'(none given)', body) + main.jobs.clear() + r, body = self.get('/pdf?name=job-19990101-000000') # even with nothing loaded at all + self.assertEqual(200, r.status) + def test_keepalive_two_requests_one_connection(self): self.send_invoice() conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) diff --git a/web/pdf.html b/web/pdf.html index 32059a1..f22f8cf 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -57,6 +57,22 @@

    Document Pages

    Plain text

    + % if sent_from_this_job: +

    Sent from this job

    +
    ToSubjectAddedFinishedProblems?
    + + % for (item, item_key) in sent_from_this_job: + + + + + + + + % endfor +
    SentDocumentToSubject
    ${item['added']}${item_key | h}${', '.join(item['to']) | h}${item['subject'] | h}${item['error'] or '' | h}
    + % endif +
    diff --git a/web/sent.html b/web/sent.html index 279d813..43a3e0a 100644 --- a/web/sent.html +++ b/web/sent.html @@ -4,19 +4,29 @@

    Sent Items

    - % if total > len(shown): -

    Showing the latest ${len(shown)} of ${total} sent emails.

    + % if total > len(rows): +

    Showing the latest ${len(rows)} of ${total} sent emails.

    % endif - - % for p in shown: + + % for row in rows: + <% p = row['p'] %> % if p['error']: % else: % endif - + + + % endfor
    ToSubjectAddedFinishedProblems?
    ToSubjectDocumentAddedFinishedProblems?
    ${'
    '.join(p['to'])}
    ${p['subject']}${p['added']}${p['completed']}${p['error']}${'
    '.join(p['to'])}
    ${p['subject']} + % if row['loaded']: + ${row['key'] | h} + ${row['job'] | h} + % elif row['job']: + ${row['key'] | h} ${row['job'] | h} + % endif + ${p['added']}${p['completed']}${p['error']}
    From 88986b3e3b986d652f652938790929e417207293 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 13:53:22 +0000 Subject: [PATCH 21/31] Sent Items: Document first as one 'job / key' link, and a smaller table The Document column is now the first column and its whole text, ' / ', is the link. The table is condensed with an 11px font to save horizontal space. Co-Authored-By: Claude Sonnet 5.5 --- test_integration.py | 5 ++++- web/sent.html | 13 ++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/test_integration.py b/test_integration.py index d41c391..27cf028 100644 --- a/test_integration.py +++ b/test_integration.py @@ -530,8 +530,11 @@ def test_sent_items_link_to_the_job_and_the_job_lists_them(self): self.assertEqual(200, r.status) self.assertNotIn(b'Mako Runtime Error', body) self.assertEqual(2, body.count(('href="/pdf?name=%s&key=ACC001"' % name).encode())) # one link per email from the loaded job - self.assertIn(b'job-20150715-101010', body) # the old job is named... + self.assertEqual(2, body.count(('>%s / ACC001' % name).encode())) # the whole "job / key" is the link text + self.assertIn(b'job-20150715-101010 / OLD001', body) # the old job is named... self.assertNotIn(b'name=job-20150715-101010', body) # ...but not linked + self.assertLess(body.index(b'Document'), body.index(b'To')) # Document is the first column + self.assertIn(b'font-size: 11px', body) # the table is set small # the job page lists the emails made from it, and only those r, body = self.get('/pdf?name=%s&key=ACC001' % name) diff --git a/web/sent.html b/web/sent.html index 43a3e0a..57c0b4e 100644 --- a/web/sent.html +++ b/web/sent.html @@ -8,8 +8,8 @@

    Sent Items

    Showing the latest ${len(rows)} of ${total} sent emails.

    % endif - - +
    ToSubjectDocumentAddedFinishedProblems?
    + % for row in rows: <% p = row['p'] %> % if p['error']: @@ -17,15 +17,14 @@

    Sent Items

    % else: % endif - - + % endfor From 2980be63a11ec91104f3683ff66048b423a0d317 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 15:53:40 +0000 Subject: [PATCH 22/31] Email templates: an 'all' helper for several documents, and use the document number When an account has several invoices in one print run (about 8% of accounts) 'doc' is only the last, so the email named one invoice and one amount while the PDF held them all. Templates now also have 'all': all.numbers (operations' subject style, '336806/7': the first number in full, then each other from the first digit that differs from the first), all.list, all.total and all.tot_* (summed exactly), all.count, all.many and all.s. It is not available to the default template. The invoice template uses doc_num, as operations do in subjects, not our ref, and reads 'New Invoice 336807' or 'New Invoices 336806/7' with each invoice and the total when there are several. Checked against the real sent history: the generated subject equals what operations typed for 166 of 167 single invoices and 14 of 17 with several; the rest are their own variations in style. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 8 ++- emailtemplates.py | 105 +++++++++++++++++++++++++++++++++--- main.py | 5 +- templates/invoice.mako | 17 ++++-- test_integration.py | 48 ++++++++++++----- web/settings_templates.html | 15 ++++-- 6 files changed, 166 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index f19ee66..bf5b4dc 100644 --- a/README.md +++ b/README.md @@ -68,8 +68,12 @@ where node isn't installed. The other templates also have: `${doc.}` (the document: `doc.ourref`, `doc.doc_num`, `doc.accno`, `doc.tot_due`, `doc.customer`, ... - the editor lists them), `${email.name}`, `${email.address}`, `${job.name}`, -`${company.name}`. If an account has several documents in one print run `doc` is the last; use -`% for d in docs:` ... `% endfor` to visit each. `% if doc.field:` / `% else:` / `% endif` and `##` comments work too. +`${company.name}`. If an account has several documents in one print run `doc` is the last, and `all` describes them together: +`${all.numbers}` writes the document numbers as operations do in a subject (`336806/7`, from the first digit +that differs from the first number), `${all.list}` as words (`336806 and 336807`), `${all.total}` is the sum +(`all.tot_due`, `all.tot_net`, `all.tot_vat` likewise), and `${all.count}`, `${all.many}` (true for several) +and `${all.s}` (`s` for several) help with wording, for example `New Invoice${all.s} ${all.numbers}`. Use +`% for d in docs:` ... `% endfor` to visit each document. `% if doc.field:` / `% else:` / `% endif` and `##` comments work too. The web interface has no authentication and Mako can run arbitrary python, so the editor only accepts that subset (no calls, operators, `<% %>` blocks or names starting with an underscore; see `emailtemplates.validate`). diff --git a/emailtemplates.py b/emailtemplates.py index 9ece716..d0e29f3 100644 --- a/emailtemplates.py +++ b/emailtemplates.py @@ -18,6 +18,7 @@ import os import re import unittest +from decimal import Decimal, InvalidOperation from mako.template import Template @@ -70,6 +71,52 @@ def merge_documents(pages): d['customer'] = d.get('addr_invoice', '').split('\n')[0].strip() return list(docs.values()) +# the field that is "the total" for each kind of document, for all.total +KIND_TOTAL = {'invoice': 'tot_due', 'purchase': 'tot_net', 'statement': 'tot_topay'} + +def collapse_numbers(numbers): + """Document numbers the way the operations team writes them in a subject: the first in full, then each of + the others from the first digit that differs from the first one onward. ['336806', '336807'] gives + '336806/7', ['336769', '336771'] gives '336769/71' and ['335909', '335910', '335911'] gives '335909/10/11'. + Numbers that aren't all digits of the same length are just listed.""" + if len(numbers) < 2 or not all(re.fullmatch(r'\d+', n) and len(n) == len(numbers[0]) for n in numbers): + return ', '.join(numbers) + first = numbers[0] + tails = [] + for n in numbers[1:]: + i = 0 + while i < len(first) - 1 and first[i] == n[i]: + i += 1 + tails.append(n[i:]) + return '/'.join([first] + tails) + +def and_list(items): + """['A'] -> 'A', ['A', 'B'] -> 'A and B', ['A', 'B', 'C'] -> 'A, B and C'""" + if len(items) < 2: + return ''.join(items) + return ', '.join(items[:-1]) + ' and ' + items[-1] + +def summarise(docs, kind): + """The 'all' helper: facts about every document of this account in the print run (docs, as dicts), so that + a subject and body can be written for one invoice or for several. + all.count, all.many ('1' if there is more than one, else ''), all.s ('s' or '': 'Invoice${all.s}') + all.numbers the document numbers as operations write them: '336806/7' + all.list the document numbers in words: '336806 and 336807' + all.total the total of all of them (invoices: amount due); all.tot_due, all.tot_net, all.tot_vat... likewise + Amounts are summed exactly and shown with two decimals. A total that isn't a plain amount is left empty.""" + numbers = [d['doc_num'] for d in docs if d.get('doc_num')] + many = len(docs) > 1 + values = {'count': str(len(docs)), 'many': '1' if many else '', 's': 's' if many else '', + 'numbers': collapse_numbers(numbers), 'list': and_list(numbers)} + for field in sorted(set(k for d in docs for k in d if k.startswith('tot_'))): + try: + amounts = [Decimal(d.get(field, '').replace(',', '')) for d in docs] + except InvalidOperation: + continue + values[field] = format(sum(amounts).quantize(Decimal('0.01')), 'f') + values['total'] = values.get(KIND_TOTAL.get(kind), '') + return Fields(values) + def account_for_key(parsed, key): """PDF group key -> account code. Purchase orders also have '-admin' and '-transport'.""" if key in parsed: @@ -94,6 +141,7 @@ def build_context(job, key, names=(), addresses=(), company=None): """The variables a template sees: doc the document (the last one, if the account has several in this print run); doc. docs every document for the account in this print run, for '% for d in docs:' + 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 @@ -109,7 +157,7 @@ def build_context(job, key, names=(), addresses=(), company=None): parsed = job.get('parsed') or {} acc = account_for_key(parsed, key) docs = merge_documents(parsed[acc]) if acc else [] - context.update(doc=Fields(docs[-1] if docs else {}), docs=[Fields(d) for d in docs]) + context.update(doc=Fields(docs[-1] if docs else {}), docs=[Fields(d) for d in docs], all=summarise(docs, kind_for_job(job))) return context def find_document(jobs, kind, term=''): @@ -142,7 +190,7 @@ def find_document(jobs, kind, term=''): _IF = re.compile(r'^\s*%%\s*if\s+(?:not\s+)?(%s)\s*:\s*$' % _PATH) _ELSE = re.compile(r'^\s*%\s*else\s*:\s*$') _END = re.compile(r'^\s*%\s*(?:endif|endfor)\s*$') -_ROOTS = frozenset(['doc', 'email', 'job', 'company']) +_ROOTS = frozenset(['doc', 'all', 'email', 'job', 'company']) _DEFAULT_ROOTS = frozenset(['email', 'job', 'company']) def validate(text, kind=None): @@ -341,11 +389,17 @@ def test_shipped_templates_are_valid_and_the_invoice_says_what_it_should(self): for kind in KINDS: text = open(seed_path(kind), encoding=ENCODING).read() self.assertEqual([], validate(text, kind), kind) - ctx = build_context(self.job(), 'HAR108', names=['Ann'], company={'name': 'ABFW'}) - message = render_message(open(seed_path('invoice'), encoding=ENCODING).read(), ctx) + text = open(seed_path('invoice'), encoding=ENCODING).read() # the wording of the shipped templates is theirs to change; these are the facts they must keep stating - self.assertTrue(message.subject.startswith('Invoice 289099 from ABFW'), message.subject) - self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your latest invoice 289099 attached for account HAR108, for \xa310\.00\.\n') + two = render_message(text, build_context(self.job(), 'HAR108', names=['Ann'], company={'name': 'ABFW'})) + self.assertEqual('New Invoices 336769/70', two.subject) # as operations write it + self.assertRegex(two.body, r'\ATo Ann,?\n\nPlease find your latest invoices attached for account HAR108, for a total of \xa31244\.50') + self.assertRegex(two.body, r'336769 +\xa31,234\.50\n336770 +\xa310\.00\n') # each invoice and its amount + one_job = self.job() + one_job['parsed'] = {'HAR108': self.pages()[2:]} + one = render_message(text, build_context(one_job, 'HAR108', names=['Ann'], company={'name': 'ABFW'})) + self.assertEqual('New Invoice 336770', one.subject) + self.assertRegex(one.body, r'\ATo Ann,?\n\nPlease find your latest invoice 336770 attached for account HAR108, for \xa310\.00\.\n') def test_shipped_templates_render_with_no_data_at_all(self): for kind in KINDS: @@ -483,6 +537,41 @@ def test_the_subject_is_the_first_rendered_line_so_it_can_be_computed(self): # a template whose first line is blank has no subject, and nothing else moves up into its place self.assertEqual(('', 'Hi\n'), tuple(render_message('\nHi\n', ctx))) + def test_collapse_numbers_matches_the_operations_convention(self): + for numbers, want in ( + ([], ''), (['336806'], '336806'), (['336806', '336807'], '336806/7'), (['336829', '336830'], '336829/30'), + (['336769', '336771'], '336769/71'), (['336696', '336698'], '336696/8'), (['336813', '336814', '336815'], '336813/4/5'), + (['335909', '335910', '335911'], '335909/10/11'), (['331279', '331280', '331282'], '331279/80/82'), + (['332058', '332059', '332060', '332061', '332066'], '332058/9/60/61/66'), + # numbers that can't be abbreviated are just listed + (['99999', '100000'], '99999, 100000'), (['34529/ 1', '34529/ 2'], '34529/ 1, 34529/ 2')): + self.assertEqual(want, collapse_numbers(numbers), numbers) + + def test_summarise_all_documents(self): + docs = [{'doc_num': '336806', 'tot_due': '569.73', 'tot_net': '474.78', 'tot_vat': '94.95'}, + {'doc_num': '336807', 'tot_due': '44.92', 'tot_net': '37.44', 'tot_vat': '7.48'}] + a = summarise(docs, 'invoice') + self.assertEqual(('2', '1', 's', '336806/7', '336806 and 336807'), (a.count, a.many, a.s, a.numbers, a.list)) + self.assertEqual(('614.65', '614.65', '512.22', '102.43'), (a.total, a.tot_due, a.tot_net, a.tot_vat)) + one = summarise(docs[:1], 'invoice') + self.assertEqual(('1', '', '', '336806', '569.73'), (one.count, one.many, one.s, one.numbers, one.total)) + # amounts are added exactly, with or without thousands separators + self.assertEqual('0.30', summarise([{'tot_due': '0.1'}, {'tot_due': '0.2'}], 'invoice').total) + self.assertEqual('1235.00', summarise([{'tot_due': '1,234.50'}, {'tot_due': '0.50'}], 'invoice').total) + # something that isn't a plain amount is left out rather than guessed at + self.assertEqual('', summarise([{'tot_due': '5.00'}, {'tot_due': 'CR'}], 'invoice').total) + # statements have no document number; their total is the amount to pay + st = summarise([{'accno': 'A', 'tot_topay': '3485.99'}], 'statement') + self.assertEqual(('', '3485.99', '1'), (st.numbers, st.total, st.count)) + self.assertEqual(('', '', ''), (summarise([], 'invoice').numbers, summarise([], 'invoice').total, summarise([], 'invoice').many)) + + def test_all_exists_for_documents_with_fields_but_not_for_the_default_template(self): + ctx = build_context(self.job(), 'HAR108', names=['Ann']) + self.assertEqual(('2', '336769/70', '336769 and 336770'), (ctx['all'].count, ctx['all'].numbers, ctx['all'].list)) + self.assertEqual([], validate('${all.numbers} ${all.total}\n% if all.many:\nx\n% endif', 'invoice')) + self.assertTrue(validate('${all.numbers}', DEFAULT)) + self.assertNotIn('all', build_context({'templ': 'delnote'}, 'X')) + def test_validate_reports_unbalanced_blocks(self): self.assertTrue(validate('% if doc.a:\nx\n')) @@ -518,8 +607,8 @@ def test_a_broken_custom_template_falls_back_to_the_shipped_one(self): with open(user_path('invoice'), 'w') as f: f.write('${__import__("os")}') # written to disk behind the editor's back message, kind, warning = render_for_job(self.job(), 'HAR108', ['Ann']) - self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your latest invoice') - self.assertTrue(message.subject.startswith('Invoice 289099')) + self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your latest invoices? ') + self.assertTrue(message.subject.startswith('New Invoice'), message.subject) self.assertIn('could not be used', warning) finally: import shutil diff --git a/main.py b/main.py index df93814..a4bb9c1 100755 --- a/main.py +++ b/main.py @@ -359,7 +359,7 @@ def settings_templates(query_string='', postreq=None, resp=None): # (for the default template: the newest other document, or the job name / document type that matches) found = emailtemplates.find_document(jobs, kind, term) is_default = kind == emailtemplates.DEFAULT - preview, preview_subject, preview_job, preview_acc, fields, names = None, None, None, None, [], [] + preview, preview_subject, preview_job, preview_acc, fields, summary_fields, names = None, None, None, None, [], [], [] if not found: what = 'document' if is_default else '%s document' % emailtemplates.KINDS[kind].lower() preview_note = 'No %s found%s.' % (what, (' matching "%s"' % term) if term else '') @@ -369,6 +369,7 @@ def settings_templates(query_string='', postreq=None, resp=None): names = list(contacts.values()) ctx = emailtemplates.build_context(preview_job, preview_acc, names=names, addresses=list(contacts.keys()), company=company_info()) fields = emailtemplates.field_names(ctx['doc']) if 'doc' in ctx else [] + summary_fields = emailtemplates.field_names(ctx['all']) if 'all' in ctx else [] preview_note = None try: rendered = emailtemplates.render_message(text, ctx, kind) @@ -379,7 +380,7 @@ def settings_templates(query_string='', postreq=None, resp=None): return ( template_lookup.get_template("/settings_templates.html").render( kinds=emailtemplates.KINDS, kind=kind, text=text, source=source, filename=os.path.basename(emailtemplates.user_path(kind)), term=term, message=message, errors=errors, preview=preview, preview_subject=preview_subject, preview_note=preview_note, - preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, is_default=is_default), 'text/html') + preview_job=preview_job, preview_acc=preview_acc, names=names, fields=fields, summary_fields=summary_fields, is_default=is_default), 'text/html') def email_body(query_string=dict(), resp=None): """The suggested email text for a document if only the contacts whose addresses are in 'em' are diff --git a/templates/invoice.mako b/templates/invoice.mako index 59115eb..1675677 100644 --- a/templates/invoice.mako +++ b/templates/invoice.mako @@ -1,5 +1,16 @@ -Invoice ${doc.ourref} from ${company.name} +New Invoice${all.s} ${all.numbers} -To ${email.name} +To ${email.name}, -Please find your latest invoice ${doc.ourref} attached for account ${doc.accno}, for £${doc.tot_due}. +% if all.many: +Please find your latest invoices attached for account ${doc.accno}, for a total of £${all.total}: + +% for d in docs: +${d.doc_num} £${d.tot_due} +% endfor +% else: +Please find your latest invoice ${doc.doc_num} attached for account ${doc.accno}, for £${doc.tot_due}. +% endif + +Kind regards +${company.name} diff --git a/test_integration.py b/test_integration.py index 27cf028..85ed98d 100644 --- a/test_integration.py +++ b/test_integration.py @@ -28,16 +28,17 @@ def put(lines, row, col, text): line = lines[row + i] lines[row + i] = line[:col] + part + line[col + len(part):] -def make_invoice(doc_num='12345', acc='ACC001', pages=2): +def make_invoice(doc_num='12345', acc='ACC001', pages=2, doc_nums=None, totals=None): """A synthetic Invoice print: 48 blank lines, then 48 lines per page. Each page ends in a form feed, - and the totals carry an 8-bit pound sign as the Windows print driver sends it.""" + and the totals carry an 8-bit pound sign as the Windows print driver sends it. By default every page is + part of invoice doc_num; doc_nums gives each page its own invoice (and totals its own amount).""" lines = [' ' * 130 for _ in range(48 * (pages + 1))] for p in range(pages): base = (p + 1) * 48 put(lines, base + 0, 0, 'INVOICE') put(lines, base + 0, 95, '01/10/26') put(lines, base + 2, 95, 'Page %d' % (p + 1)) - put(lines, base + 4, 95, doc_num) + put(lines, base + 4, 95, doc_nums[p] if doc_nums else doc_num) put(lines, base + 8, 12, 'ACME WINES LTD\n1 HIGH STREET\nLONDON') put(lines, base + 16, 0, acc) put(lines, base + 16, 9, 'PO-7') @@ -45,7 +46,7 @@ def make_invoice(doc_num='12345', acc='ACC001', pages=2): put(lines, base + 19, 0, 'B0321021\nB0308206') put(lines, base + 19, 19, 'BAUCHET Customer Label\nDRAPPIER Carte D\'Or') put(lines, base + 19, 55, '12\n6') - put(lines, base + 42, 89, '\xa3123.45') + put(lines, base + 42, 89, totals[p] if totals else '\xa3123.45') lines[base + 47] = lines[base + 47][:100] + '\x0c' return '\r\n'.join(lines) + '\r\n' @@ -253,10 +254,10 @@ def test_recent_json_ts_is_per_job(self): self.assertEqual(second['ts'].isoformat(), rows[second['name']]['ts']) # The wording of the shipped templates is theirs to change, so these check the facts rather than every word - INVOICE_SUBJECT_START = 'Invoice 289073 from' + INVOICE_SUBJECT = r'New Invoice \d+' # 'New Invoice 12345', as operations write it - def assertInvoiceBody(self, page, names, msg=None): - self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your latest invoice 289073 attached for account ACC001, for \xa3123\.45\.' % re.escape(names), msg) + def assertInvoiceBody(self, page, names, doc_num='12345', msg=None): + self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your latest invoice %s attached for account ACC001, for \xa3123\.45\.' % (re.escape(names), doc_num), msg) def assertDefaultBody(self, page, names, msg=None): self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your document attached\.' % re.escape(names), msg) @@ -270,8 +271,8 @@ def test_compose_form_is_prefilled_from_the_invoice_template(self): self.assertEqual(200, r.status) self.assertNotIn(b'Mako Runtime Error', body) self.assertInvoiceBody(body, 'Sir or Madam') - self.assertSubjectBox(body, re.escape(self.INVOICE_SUBJECT_START) + '[^"]*') - self.assertNotRegex(body.decode('utf-8'), re.escape(self.INVOICE_SUBJECT_START) + '[^<\n]*\n\n?To ') # the subject is not repeated in the text + self.assertSubjectBox(body, self.INVOICE_SUBJECT) + self.assertNotRegex(body.decode('utf-8'), self.INVOICE_SUBJECT + '[^<\n]*\n\n?To ') # the subject is not repeated in the text self.assertIn(b'/settings/templates?kind=invoice&docnum=12345', body) # with contacts on the account the greeting names them, and html in a name is escaped in the textarea self.get('/settings/email?account=ACC001&email=a%40example.com&contact=Ann') @@ -301,7 +302,7 @@ def test_template_editor_preview_save_and_revert(self): self.assertNotIn(b'Mako Runtime Error', body) self.assertIn(b'

    Template invoice.mako

    ', body) self.assertNotIn(b'Revert to default', body) # nothing customised yet, so nothing to revert - self.assertIn(b'Please find your latest invoice 289073 attached', body) # preview of the newest invoice + self.assertIn(b'Please find your latest invoice 424242 attached', body) # preview of the newest invoice for kind in ('purchase', 'statement'): r, body = self.get('/settings/templates?kind=' + kind) self.assertEqual(200, r.status) @@ -345,8 +346,8 @@ def test_template_editor_preview_save_and_revert(self): self.assertIn(b'Reverted to the shipped invoice template', body) self.assertFalse(os.path.exists(path)) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) - self.assertInvoiceBody(body, 'Sir or Madam') - self.assertSubjectBox(body, re.escape(self.INVOICE_SUBJECT_START) + '[^"]*') + self.assertInvoiceBody(body, 'Sir or Madam', doc_num='424242') + self.assertSubjectBox(body, self.INVOICE_SUBJECT) def test_template_editor_refuses_templates_that_could_run_code(self): self.send_invoice() @@ -383,12 +384,12 @@ def body(*ticked): self.assertIsNone(answer['warning']) return answer['body'] - self.assertRegex(body('ann@x.com', 'bob@x.com'), r'\ATo Ann and Bob,?\n\nPlease find your latest invoice 289073') + self.assertRegex(body('ann@x.com', 'bob@x.com'), r'\ATo Ann and Bob,?\n\nPlease find your latest invoice 12345') self.assertRegex(body('bob@x.com'), r'\ATo Bob,?\n\nPlease find') self.assertRegex(body(), r'\ATo Sir or Madam,?\n\nPlease find') # nobody ticked self.assertRegex(body('stranger@x.com'), r'\ATo Sir or Madam,?\n') # not in the address book: no name to use query = 'name=%s&key=ACC001&em=bob%%40x.com&em=ann%%40x.com' % j['name'] - self.assertTrue(json.loads(self.get('/email_body?' + query)[1].decode())['subject'].startswith(self.INVOICE_SUBJECT_START)) + self.assertTrue(json.loads(self.get('/email_body?' + query)[1].decode())['subject'].startswith('New Invoice ')) # subject and body both follow the recipients: first line is the subject, the rest the body self.post('/settings/templates', kind='invoice', action='save', template='For ${email.name}\n\n${email.name} <${email.address}>') answer = json.loads(self.get('/email_body?' + query)[1].decode()) @@ -552,6 +553,25 @@ def test_sent_items_link_to_the_job_and_the_job_lists_them(self): finally: mailer_results()[:] = original + def test_several_invoices_for_one_account_make_one_email(self): + # two invoices for one account in one print run, as for VAD101: one PDF, one email + j = self.send_invoice(doc_nums=['777', '778'], totals=['\xa3569.73', '\xa344.92']) + self.assertEqual(['777', '778'], [p['doc_num'] for p in j['parsed']['ACC001']]) + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertNotIn(b'Mako Runtime Error', body) + self.assertSubjectBox(body, 'New Invoices 777/8') + page = body.decode('utf-8') + self.assertRegex(page, r'Please find your latest invoices attached for account ACC001, for a total of \xa3614\.65:') + self.assertRegex(page, r'777 +\xa3569\.73\n778 +\xa344\.92\n') + self.assertNotIn('\xa344.92.', page) # not "for \xa344.92", the last invoice alone + # the live update and the editor preview say the same + answer = json.loads(self.get('/email_body?name=%s&key=ACC001' % j['name'])[1].decode()) + self.assertEqual('New Invoices 777/8', answer['subject']) + self.assertIn('for a total of \xa3614.65', answer['body']) + r, body = self.get('/settings/templates?kind=invoice&docnum=778') + self.assertIn(b'Subject: New Invoices 777/8', body) + self.assertIn(b'all.numbers', body) # the helper is listed in the editor + def test_pdf_page_for_a_job_that_is_not_loaded_is_a_message_not_an_error(self): self.send_invoice() r, body = self.get('/pdf?name=job-19990101-000000') diff --git a/web/settings_templates.html b/web/settings_templates.html index db9c022..9c57892 100644 --- a/web/settings_templates.html +++ b/web/settings_templates.html @@ -95,6 +95,13 @@

    Available fields

    ${'${job.name}'} ${'${job.doctype}'} ${'${job.host}'} ${'${company.name}'} ${'${company.email}'} ${'${company.website}'}

    +% if summary_fields: +

    About all the documents of this account in the print run: + % for f in summary_fields: + ${'${all.' + f + '}'} + % endfor +

    +% endif % if fields:

    From this document: % for f in fields: @@ -108,7 +115,9 @@

    Available fields

    The default template is used for documents whose contents printerface doesn't read, so only the recipients, the job and the company details are available. Add | trim to remove surrounding spaces.

    % else: -

    If an account has several documents in one print run, doc is the last of them; use -% for d in docs: … % endfor with ${'${d.field}'} to visit each one. -Add | trim to remove surrounding spaces.

    +

    If an account has several documents in one print run, doc is the last of them; +all describes them together, so New Invoice${'${all.s}'} ${'${all.numbers}'} reads +“New Invoice 336807” or “New Invoices 336806/7”. Use +% for d in docs: … % endfor with ${'${d.field}'} to visit each one, and +% if all.many: to word it differently for several. Add | trim to remove surrounding spaces.

    % endif From 5cec33747d89115bb45b755bc8498e151d50b929 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 17:20:14 +0000 Subject: [PATCH 23/31] Shipped email templates: greeting comma, signature, and the document type in the default subject default.mako: subject 'Document ${job.doctype} attached', 'To ,' and a 'Kind regards' signature. statement.mako: 'To ,'. Co-Authored-By: Claude Sonnet 5.5 --- templates/default.mako | 9 ++++++--- templates/statement.mako | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/templates/default.mako b/templates/default.mako index 163ef6e..6ffe6ae 100644 --- a/templates/default.mako +++ b/templates/default.mako @@ -1,5 +1,8 @@ -Document attached +Document ${job.doctype} attached -To ${email.name} +To ${email.name}, -Please find your document attached. +Please find your ${job.doctype} document attached. + +Kind regards +${company.name} diff --git a/templates/statement.mako b/templates/statement.mako index 3fce72a..477fb51 100644 --- a/templates/statement.mako +++ b/templates/statement.mako @@ -1,6 +1,6 @@ Statement dated ${doc.date} from ${company.name} -To ${email.name} +To ${email.name}, Please find attached your statement dated ${doc.date} for account ${doc.accno}. From 16c49401149804f7c8f2f0983aa06f4ca2236c30 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 18:45:06 +0000 Subject: [PATCH 24/31] Actions that change something are POSTs that redirect, so a refresh never repeats them Sending an email was a GET carrying the subject and text in the URL, so refreshing the page after sending (to see it under 'Sent from this job') sent it again. The same was true of printing a document (a plain link) and of adding or removing a contact in the address book (GET forms). * httpserver: a handler can return Redirect(location); the server answers 303 See Other. * /pdf: sending is a POST; success redirects back to the job page with a note, a refused send re-renders the form with what was typed and who was ticked. * /print: POST from a hidden form (the Print menu submits it), then back to the job page. GET shows a message. * /settings/email: adding and removing a contact are POSTs that redirect to the list. * /settings/templates: Save and Revert redirect to the editor (a refused save still re-renders with its errors). * A GET carrying the old parameters no longer does anything. * The send button disables itself on submit so a double click cannot queue the email twice. Read-only handlers (recent, job, raw, debug, plaintext, pdf_file, printers, sent, email_body) stay GET. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 ++ emailtemplates.py | 2 +- httpserver.py | 25 +++++- main.py | 136 ++++++++++++++++++-------------- test_compose.js | 23 +++++- test_integration.py | 170 ++++++++++++++++++++++++++++++++++++---- web/js/compose.js | 32 +++++++- web/pdf.html | 18 +++-- web/settings_email.html | 8 +- 9 files changed, 332 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index bf5b4dc..54b953e 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,11 @@ The following will checkout the source code, build a docker image and start an i * `stationary.py` format JSON to nice PDF files * `printing.py` Linux printing with CUPS via. command line +A GET never changes anything: sending an email, printing, editing the address book and saving or reverting a +template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303) to a page that is safe to refresh, +carrying at most a harmless note in the query string ("queued=1"). A POST that is refused re-renders the form +instead, with what was typed. New actions should follow the same pattern. + Requires **python 3.11** (3.9+ for the dependencies, but `asyncore`/`asynchat` were removed from the standard library in 3.12). Requirements are specified in requirements.txt Unit tests run during `docker build` or with: diff --git a/emailtemplates.py b/emailtemplates.py index d0e29f3..a6c09d9 100644 --- a/emailtemplates.py +++ b/emailtemplates.py @@ -412,7 +412,7 @@ def test_other_document_types_use_the_default_template(self): message, kind, warning = render_for_job({'templ': templ, 'name': 'job-9', 'doctype': 'Delvnote'}, 'X', ['Ann']) self.assertEqual((DEFAULT, None), (kind, warning), templ) self.assertRegex(message.subject, r'\ADocument\b.*attached\Z') - self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your document attached\.\n') + self.assertRegex(message.body, r'\ATo Ann,?\n\nPlease find your (?:\w+ )?document attached\.\n') def test_the_default_context_has_no_document_fields(self): ctx = build_context({'templ': 'delnote', 'name': 'job-9', 'doctype': 'Delvnote', 'control': {'H': 'PC1'}}, 'X', ['Ann'], ['a@b.c'], {'name': 'ABFW', 'email': 'sales@abfw.test'}) diff --git a/httpserver.py b/httpserver.py index 352843a..46b023b 100644 --- a/httpserver.py +++ b/httpserver.py @@ -84,6 +84,13 @@ def __contains__(self,key): def _quote_html(text): return text.replace("&", "&").replace("<", "<").replace(">", ">") +class Redirect(object): + """A path handler returns this instead of (body, content type) to answer with a redirect. It is a 303 See + Other, so the browser fetches the location with GET: after handling a POST this means the page the user ends + up on can be refreshed without repeating the POST.""" + def __init__(self, location): + self.location = location + def _body_file(f, ctype): """Normalise whatever a path handler returned into (binary file object, content type). Handlers return str (json, plain), bytes (mako output, pdf) or a binary file object.""" @@ -465,7 +472,11 @@ def write_headers(self, connection): if (handler): try: resp = ResponseGatherer() - (f, ctype) = _body_file(*handler(query_string=self.query_string, resp=resp)) + result = handler(query_string=self.query_string, resp=resp) + if isinstance(result, Redirect): + self.send_redirect(result) + return None + (f, ctype) = _body_file(*result) self.send_response(200) resp.write_headers(self) self.send_header("Content-type", ctype) @@ -516,6 +527,12 @@ def write_headers(self, connection): self.end_headers() return f + def send_redirect(self, redirect): + self.send_response(303) + self.send_header("Location", redirect.location) + self.send_header("Content-Length", "0") + self.end_headers() + def list_directory(self, path): """Helper to produce a directory listing (absent index.html). @@ -647,7 +664,11 @@ def do_POST(self): handler = self.handlers.get(self.path) if (handler): try: - (f, ctype) = _body_file(*handler(query_string=self.query_string, postreq=postreq)) + result = handler(query_string=self.query_string, postreq=postreq) + if isinstance(result, Redirect): + self.send_redirect(result) + return None + (f, ctype) = _body_file(*result) self.send_response(200) self.send_header("Content-type", ctype) f.seek(0, os.SEEK_END) diff --git a/main.py b/main.py index a4bb9c1..7368f05 100755 --- a/main.py +++ b/main.py @@ -7,7 +7,7 @@ import asynchat, asyncore, socket, os, re from datetime import datetime from lpdserver import LpdServer -from httpserver import ToyHttpServer +from httpserver import ToyHttpServer, Redirect import mailer from mailer import JobMailer from docparser import DocParser @@ -284,45 +284,46 @@ def sent(query_string='', resp=None): return ( template_lookup.get_template("/sent.html").render(rows=rows, total=len(results)), 'text/html') def settings_email(query_string='', postreq=None, resp=None): - warning=None - print('query_string=%s' % query_string) - try: - acc = query_string['account'][0] - email = query_string['email'][0] - contact = query_string['contact'][0] - try: - email_accounts[acc] - if not email.strip() in email_addresses[acc]: - email_addresses[acc][email.strip()] = contact + """The address book. Adding and removing a contact change it, so they only happen on a POST, which then + redirects back here: a refresh (or a bookmarked URL) shows the list and never repeats the change.""" + if postreq is not None: + account = postreq.get('account', [''])[0] + warning = None + if 'delete' in postreq: + if email_addresses[account].pop(postreq['delete'][0], None): saveEmails() - except KeyError: - warning='Unknown account %s' % acc - except KeyError: - pass - - try: - acc = query_string['account'][0] - delete_email = query_string['delete'][0] - if email_addresses[acc].pop(delete_email, None): - saveEmails() - except KeyError: - pass + elif 'email' in postreq and 'contact' in postreq: + email = postreq['email'][0].strip() + if account not in email_accounts: + warning = 'Unknown account %s' % account + elif email not in email_addresses[account]: + email_addresses[account][email] = postreq['contact'][0] + saveEmails() + return Redirect('/settings/email' + ('?' + urllib.parse.urlencode({'warning': warning}) if warning else '')) + warning = html.escape(query_string.get('warning', [''])[0]) or None email_list = [] for key in sorted(email_accounts): email_list.append( (key, email_accounts[key], list(email_addresses[key].items())) ) return ( template_lookup.get_template("/settings_email.html").render(emails=email_list, warning=warning), 'text/html') -def printfn(query_string='', resp=None): - docf = getJobFile(query_string) - if docf: +def printfn(query_string='', postreq=None, resp=None): + """Print a document on one of the printers. Paper comes out, so only a POST does it, and it redirects back + to the job page so that a refresh doesn't print it again.""" + if postreq is None: + return doMessage(title='Printing', message='Documents are printed from their job page.') + job = getJob(postreq) + docf = getJobFile(postreq, job) + printer = postreq.get('printer', [''])[0] + if docf and printer: try: - printFile(pdfdir + docf, ''.join(query_string['printer']) ) - return doMessage(title='Printing', message='Document %s sent to printer %s
    ' % (docf, query_string['printer'])) - except: + printFile(pdfdir + docf, printer) + key = postreq.get('key', [next(iter(job['groupfiles']))[0]])[0] + return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'printed': printer})) + except Exception: traceback.print_exc(file=sys.stdout) - return doMessage(title='Printing', message='Could not find document, problem printing! Source: %s sent to printer %s
    ' % (docf, query_string['printer'])) + 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='') @@ -340,20 +341,29 @@ def settings_templates(query_string='', postreq=None, resp=None): term = params.get('docnum', '').strip() action = params.get('action', '') if posted else '' + def back(**flash): + return Redirect('/settings/templates?' + urllib.parse.urlencode(dict(kind=kind, docnum=term, **flash))) + text, source = emailtemplates.load(kind) message, errors = None, [] if action == 'revert': - message = 'Reverted to the shipped %s template.' % emailtemplates.KINDS[kind].lower() if emailtemplates.revert(kind) else 'Already using the shipped template.' - text, source = emailtemplates.load(kind) + return back(reverted='1' if emailtemplates.revert(kind) else '0') elif action in ('preview', 'save'): text = params.get('template', '').replace('\r\n', '\n').replace('\r', '\n') if action == 'save': try: emailtemplates.save(kind, text) - text, source = emailtemplates.load(kind) - message = 'Saved the %s template.' % emailtemplates.KINDS[kind].lower() + return back(saved='1') except emailtemplates.TemplateError as e: errors = e.errors + elif not posted: + # back from a save or revert: the redirect only says which + if params.get('saved'): + message = 'Saved the %s template.' % emailtemplates.KINDS[kind].lower() + elif params.get('reverted') == '1': + message = 'Reverted to the shipped %s template.' % emailtemplates.KINDS[kind].lower() + elif params.get('reverted') == '0': + message = 'Already using the shipped template.' # preview: the newest document of this type, or the one whose document number / account matches the filter # (for the default template: the newest other document, or the job name / document type that matches) @@ -395,40 +405,49 @@ def email_body(query_string=dict(), resp=None): job, key, names=[known[a] for a in ticked if a in known], addresses=ticked, company=company_info()) return json.dumps({'subject': message.subject, 'body': message.body, 'warning': warning}), 'text/json' -def pdf(query_string=dict(), resp=None): - job = getJob(query_string) +def pdf(query_string=dict(), postreq=None, resp=None): + """A job's document page. Sending the email is a POST (the form); it redirects back here, so a refresh of + the page never sends it again. A GET only ever shows the page.""" + params = dict(query_string) + if postreq is not None: + params.update(postreq) + job = getJob(params) if not job.get('groupfiles'): - name = query_string.get('name', [''])[0] + name = params.get('name', [''])[0] return doMessage(title='Job not found', message='There is no job %s loaded. Only the most recent jobs are kept in memory, so older ones ' 'can\'t be opened here. Recent jobs' % (html.escape(name) or '(none given)')) default_key = next(iter(job['groupfiles']))[0] - key = query_string.get('key', [default_key])[0] + key = params.get('key', [default_key])[0] email_dest = email_addresses.get(key, {}) email_outcome, email_error = None, None + typed = None # what the user typed, kept if the send is refused so that nothing has to be retyped - # test if callback from email form - try: - addresses = query_string.get('em', []) - email_body = ''.join(query_string.get('emailbody', [''])) - email_subject = ''.join(query_string.get('subject', ['no subject'])) - action = query_string.get('action', None) - - docf = getJobFile(query_string) - + if postreq is not None and params.get('action', [''])[0] == 'send': + addresses = params.get('em', []) + email_subject = ''.join(params.get('subject', [''])) + email_body = ''.join(params.get('emailbody', [''])) + docf = getJobFile(params, job) if len(addresses) > 0 and docf and len(email_subject) > 1: - email_outcome = "Queueing email to " + ','.join(addresses) + ' - check the result later!'; - print(email_outcome) try: - mailqueue.append(dict( - to=addresses, body=email_body, subject=email_subject, - attachment=pdfdir + docf)) - except: + mailqueue.append(dict(to=addresses, body=email_body, subject=email_subject, attachment=pdfdir + docf)) + print('Queueing email to ' + ','.join(addresses)) + return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'queued': len(addresses)})) + except Exception: traceback.print_exc(file=sys.stdout) email_error = "Problem! unable to queue email!" - elif action: + else: email_error = "Oh snap! Some fields missing or incomplete!" - except: - raise + typed = dict(subject=email_subject, body=email_body, ticked=addresses) + elif postreq is None: + # a redirect from a send or a print lands here; the note only says what happened + try: + queued = int(query_string.get('queued', ['0'])[0]) + except ValueError: + queued = 0 + if queued: + email_outcome = 'Queued the email to %d recipient%s. It is listed under "Sent from this job" once it has gone.' % (queued, '' if queued == 1 else 's') + elif query_string.get('printed'): + email_outcome = 'Sent the document to printer %s.' % html.escape(query_string['printed'][0]) # the suggested subject and body come from the template for this type of document (or the default template) email_subject_default, email_body_default = '', '' @@ -440,6 +459,9 @@ def pdf(query_string=dict(), resp=None): except Exception: traceback.print_exc(file=sys.stdout) template_warning = 'The email template for this document could not be used.' + if typed: + email_subject_default, email_body_default = typed['subject'], typed['body'] + # emails made from this job that are still in the sent history, newest first sent_from_this_job = mailer.sent_from_job(mailqueue.results, job['name']) @@ -451,7 +473,7 @@ def pdf(query_string=dict(), resp=None): pages = parsed.get(emailtemplates.account_for_key(parsed, key)) or [{}] template_docnum = pages[0].get('doc_num', '').strip() - return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, + return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, ticked=typed['ticked'] if typed else None, template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') diff --git a/test_compose.js b/test_compose.js index f4d9311..bbda915 100644 --- a/test_compose.js +++ b/test_compose.js @@ -1,6 +1,6 @@ // Tests for web/js/compose.js with a minimal stand-in for the DOM. Run by test_compose_js.py, or: node test_compose.js const assert = require('assert'); -const {init} = require('./web/js/compose.js'); +const {init, initPrint, initSend} = require('./web/js/compose.js'); function element(props) { const handlers = {}; @@ -124,5 +124,26 @@ const untick = (t, i) => { t.boxes[i].checked = false; t.boxes[i].fire('change') // a page without the compose form is left alone assert.strictEqual(setup(['a@x.com'], 'x', {url: null}).api, undefined); + // printing posts a form: choosing a printer fills it in and submits it, and the click itself is cancelled + const submitted = []; + const printerField = {value: ''}; + const printForm = {elements: {printer: printerField}, submit() { submitted.push(printerField.value); }}; + const clickHandlers = []; + const printItem = {getAttribute: () => 'HP_TONY', addEventListener: (type, fn) => clickHandlers.push(fn)}; + initPrint({getElementById: id => ({printForm}[id]), querySelectorAll: () => [printItem]}); + let prevented = 0; + clickHandlers[0]({preventDefault() { prevented++; }}); + assert.deepStrictEqual([submitted, prevented], [['HP_TONY'], 1]); + assert.strictEqual(initPrint({getElementById: () => null, querySelectorAll: () => []}), undefined); // no print form: nothing to do + + // the send button is disabled as the form is submitted, so a double click can't send twice + const sendButton = {disabled: false}; + let onSubmit; + initSend({getElementById: id => id === 'composeForm' ? {addEventListener: (type, fn) => { if (type === 'submit') onSubmit = fn; }} : sendButton}); + assert.strictEqual(sendButton.disabled, false); + onSubmit(); + assert.strictEqual(sendButton.disabled, true); + assert.strictEqual(initSend({getElementById: () => null}), undefined); + console.log('compose.js: all tests passed'); })().catch(e => { console.error(e); process.exit(1); }); diff --git a/test_integration.py b/test_integration.py index 85ed98d..123b8f6 100644 --- a/test_integration.py +++ b/test_integration.py @@ -117,13 +117,25 @@ def get(self, path, headers=None): def post(self, path, **fields): conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) - body = urllib.parse.urlencode(fields).encode('utf-8') + body = urllib.parse.urlencode(fields, doseq=True).encode('utf-8') conn.request('POST', path, body=body, headers={'Content-Type': 'application/x-www-form-urlencoded'}) r = conn.getresponse() data = r.read() conn.close() return r, data + def post_redirect(self, path, **fields): + """POST, expect the 303 that sends the browser back to a GET page, and return (location, that page).""" + r, data = self.post(path, **fields) + self.assertEqual(303, r.status, data[:300]) + location = r.getheader('Location') + r2, page = self.get(location) + self.assertEqual(200, r2.status, location) + return location, page + + def add_contact(self, account, email, name): + self.post_redirect('/settings/email', account=account, email=email, contact=name) + def setUp(self): main.jobs.clear() main.email_addresses.clear() @@ -232,15 +244,15 @@ def test_http_endpoints(self): def test_email_settings_with_non_ascii_contact(self): self.send_invoice() - r, body = self.get('/settings/email?account=ACC001&email=jose%40example.com&contact=Jos%C3%A9') - self.assertEqual(200, r.status) + location, body = self.post_redirect('/settings/email', account='ACC001', email='jose@example.com', contact='Jos\xe9') + self.assertEqual('/settings/email', location) self.assertIn('Jos\xe9'.encode('utf-8'), body) self.assertEqual('Jos\xe9', main.email_addresses['ACC001']['jose@example.com']) # saved address book reloads main.email_addresses.clear() main.recover() self.assertEqual('Jos\xe9', main.email_addresses['ACC001']['jose@example.com']) - r, body = self.get('/settings/email?account=ACC001&delete=jose%40example.com') + location, body = self.post_redirect('/settings/email', account='ACC001', delete='jose@example.com') self.assertNotIn(b'jose@example.com', body) def test_recent_json_ts_is_per_job(self): @@ -260,7 +272,7 @@ def assertInvoiceBody(self, page, names, doc_num='12345', msg=None): self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your latest invoice %s attached for account ACC001, for \xa3123\.45\.' % (re.escape(names), doc_num), msg) def assertDefaultBody(self, page, names, msg=None): - self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your document attached\.' % re.escape(names), msg) + self.assertRegex(page.decode('utf-8'), r'To %s,?\n\nPlease find your (?:\w+ )?document attached\.' % re.escape(names), msg) def assertSubjectBox(self, page, pattern, msg=None): self.assertRegex(page.decode('utf-8'), r'name="subject" placeholder="Subject" value="%s"' % pattern, msg) @@ -275,8 +287,8 @@ def test_compose_form_is_prefilled_from_the_invoice_template(self): self.assertNotRegex(body.decode('utf-8'), self.INVOICE_SUBJECT + '[^<\n]*\n\n?To ') # the subject is not repeated in the text self.assertIn(b'/settings/templates?kind=invoice&docnum=12345', body) # with contacts on the account the greeting names them, and html in a name is escaped in the textarea - self.get('/settings/email?account=ACC001&email=a%40example.com&contact=Ann') - self.get('/settings/email?account=ACC001&email=b%40example.com&contact=Bob+%26+Co') + self.add_contact('ACC001', 'a@example.com', 'Ann') + self.add_contact('ACC001', 'b@example.com', 'Bob & Co') r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertInvoiceBody(body, 'Ann and Bob & Co') @@ -329,8 +341,9 @@ def test_template_editor_preview_save_and_revert(self): self.assertIn(b'Just text', body) # save writes the user template, and the compose form then uses it - r, body = self.post('/settings/templates', kind='invoice', action='save', docnum='', + location, body = self.post_redirect('/settings/templates', kind='invoice', action='save', docnum='', template='Dear ${email.name}\r\nInvoice ${doc.doc_num}\r\n') + self.assertEqual('/settings/templates?kind=invoice&docnum=&saved=1', location) self.assertIn(b'Saved the invoice template', body) self.assertIn(b'

    Template invoice.mako

    ', body) # the same line, customised or not self.assertIn(b'Revert to default', body) @@ -342,8 +355,10 @@ def test_template_editor_preview_save_and_revert(self): self.assertNotIn(b'Dear Sir or Madam\nInvoice', body) # revert goes back to the shipped text - r, body = self.post('/settings/templates', kind='invoice', action='revert') + location, body = self.post_redirect('/settings/templates', kind='invoice', action='revert') self.assertIn(b'Reverted to the shipped invoice template', body) + for _ in range(2): # refreshing the page after it just says the same + self.assertIn(b'Reverted to the shipped invoice template', self.get(location)[1]) self.assertFalse(os.path.exists(path)) r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertInvoiceBody(body, 'Sir or Madam', doc_num='424242') @@ -367,13 +382,15 @@ def test_template_editor_refuses_templates_that_could_run_code(self): self.assertFalse(os.path.exists(canary), text) # the kind comes from a fixed list, never from a path r, body = self.post('/settings/templates', kind='../../etc/passwd', action='save', template='x') - self.assertEqual(200, r.status) + self.assertEqual(303, r.status) + self.assertIn('kind=invoice', r.getheader('Location')) # an unknown kind means the first one, not a path self.assertFalse(os.path.exists(os.path.join(emailtemplates.USER_DIR, '..', '..', 'etc'))) + self.assertEqual(['invoice.mako'], os.listdir(emailtemplates.USER_DIR)) def test_email_body_follows_the_ticked_contacts(self): j = self.send_invoice() - self.get('/settings/email?account=ACC001&email=ann%40x.com&contact=Ann') - self.get('/settings/email?account=ACC001&email=bob%40x.com&contact=Bob') + self.add_contact('ACC001', 'ann@x.com', 'Ann') + self.add_contact('ACC001', 'bob@x.com', 'Bob') def body(*ticked): query = ['name=' + j['name'], 'key=ACC001'] + ['em=' + urllib.parse.quote(e) for e in ticked] @@ -399,7 +416,7 @@ def body(*ticked): def test_compose_form_is_wired_for_live_updates(self): j = self.send_invoice() - self.get('/settings/email?account=ACC001&email=bob%40x.com&contact=Bob+%26+Co') + self.add_contact('ACC001', 'bob@x.com', 'Bob & Co') r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertNotIn(b'Mako Runtime Error', body) self.assertIn(('data-url="/email_body?name=%s&key=ACC001"' % j['name']).encode(), body) @@ -442,11 +459,11 @@ def test_default_template_editor(self): r, body = self.post('/settings/templates', kind='default', action='save', template=text) self.assertIn(b"This template can", body, text) self.assertFalse(os.path.exists(emailtemplates.user_path('default')), text) - r, body = self.post('/settings/templates', kind='default', action='save', template='Hello ${email.name}, re ${job.doctype}') + location, body = self.post_redirect('/settings/templates', kind='default', action='save', template='Hello ${email.name}, re ${job.doctype}') self.assertIn(b'Saved the default template', body) r, body = self.get('/pdf?name=' + j['name']) self.assertIn(b'Hello Sir or Madam, re Delvnote', body) - r, body = self.post('/settings/templates', kind='default', action='revert') + location, body = self.post_redirect('/settings/templates', kind='default', action='revert') self.assertIn(b'Reverted to the shipped default template', body) r, body = self.get('/pdf?name=' + j['name']) self.assertDefaultBody(body, 'Sir or Madam') @@ -572,6 +589,129 @@ def test_several_invoices_for_one_account_make_one_email(self): self.assertIn(b'Subject: New Invoices 777/8', body) self.assertIn(b'all.numbers', body) # the helper is listed in the editor + # ---- anything that changes something is a POST, and redirects to a page that is safe to refresh + + def test_sending_an_email_is_a_post_that_redirects(self): + from unittest import mock + j = self.send_invoice() + self.add_contact('ACC001', 'ann@x.com', 'Ann') + fields = dict(name=j['name'], key='ACC001', action='send', subject='Hello there', emailbody='The text') + with mock.patch.object(main.mailqueue, 'append') as append: + # a GET carrying every send parameter only shows the page: it must never send + r, body = self.get('/pdf?' + urllib.parse.urlencode(dict(fields, em='ann@x.com'))) + self.assertEqual(200, r.status) + self.assertNotIn(b'Queued the email', body) + append.assert_not_called() + + # the POST queues it once and answers with a redirect to the page + r, data = self.post('/pdf', em=['ann@x.com'], **fields) + self.assertEqual(303, r.status) + self.assertEqual('0', r.getheader('Content-Length')) + location = r.getheader('Location') + self.assertEqual('/pdf?name=%s&key=ACC001&queued=1' % j['name'], location) + append.assert_called_once() + item = append.call_args[0][0] + self.assertEqual((['ann@x.com'], 'Hello there', 'The text'), (item['to'], item['subject'], item['body'])) + self.assertTrue(item['attachment'].endswith('-ACC001.pdf'), item['attachment']) + + # the page it lands on says so; refreshing it (or following the link again) sends nothing more + for _ in range(3): + r, body = self.get(location) + self.assertEqual(200, r.status) + self.assertIn(b'Queued the email to 1 recipient.', body) + append.assert_called_once() + + def test_a_refused_send_keeps_what_was_typed_and_who_was_ticked(self): + from unittest import mock + j = self.send_invoice() + self.add_contact('ACC001', 'ann@x.com', 'Ann') + self.add_contact('ACC001', 'bob@x.com', 'Bob') + with mock.patch.object(main.mailqueue, 'append') as append: + r, data = self.post('/pdf', name=j['name'], key='ACC001', action='send', em=['bob@x.com'], subject='x', emailbody='my own words') + self.assertEqual(200, r.status) # not a redirect: nothing happened, so say why here + page = data.decode('utf-8') + self.assertIn('Some fields missing or incomplete', page) + self.assertIn('my own words', page) + self.assertRegex(page, r'name="subject" placeholder="Subject" value="x"') + self.assertRegex(page, r'value="bob@x.com" checked') + self.assertNotRegex(page, r'value="ann@x.com" checked') + append.assert_not_called() + # no recipient at all is refused too + r, data = self.post('/pdf', name=j['name'], key='ACC001', action='send', subject='Hello there', emailbody='text') + self.assertEqual(200, r.status) + append.assert_not_called() + + def test_printing_is_a_post_that_redirects(self): + from unittest import mock + j = self.send_invoice() + with mock.patch.object(main, 'printFile') as printed: + r, body = self.get('/print?name=%s&key=ACC001&printer=default' % j['name']) # the old kind of link + self.assertEqual(200, r.status) + printed.assert_not_called() + self.assertIn(b'printed from their', body) + + r, data = self.post('/print', name=j['name'], key='ACC001', printer='default') + self.assertEqual(303, r.status) + location = r.getheader('Location') + self.assertEqual('/pdf?name=%s&key=ACC001&printed=default' % j['name'], location) + printed.assert_called_once() + self.assertTrue(printed.call_args[0][0].endswith('-ACC001.pdf')) + self.assertEqual('default', printed.call_args[0][1]) + for _ in range(2): + self.assertIn(b'Sent the document to printer default.', self.get(location)[1]) + printed.assert_called_once() + # the job page offers printers through a POST form, not links + r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) + self.assertIn(b'Document Pages % endfor + + + + + +
    DocumentToSubjectAddedFinishedProblems?
    ${'
    '.join(p['to'])}
    ${p['subject']} + % if row['loaded']: - ${row['key'] | h} - ${row['job'] | h} + ${row['job'] | h} / ${row['key'] | h} % elif row['job']: - ${row['key'] | h} ${row['job'] | h} + ${row['job'] | h} / ${row['key'] | h} % endif ${'
    '.join(p['to'])}
    ${p['subject']} ${p['added']}${p['completed']}${p['error']}
    % endif -
    - - + + + @@ -130,7 +136,7 @@

    Compose Email

    diff --git a/web/settings_email.html b/web/settings_email.html index b6925cc..f989896 100644 --- a/web/settings_email.html +++ b/web/settings_email.html @@ -13,7 +13,7 @@

    Warning

    % endif -
    +
    @@ -44,9 +44,9 @@

    Existing Entries

    % endif % for (em,cn) in addresses: - - - + + + ${cn} ${em} From 8f52defc7c186ff994f6b80235633eca16353a46 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 21:34:28 +0000 Subject: [PATCH 25/31] Remove the dead PDF Tool send form from the plain text page plain.html carried a modal with an email form (method=get, action=send) holding hard-coded sample values ('blah blah', 'Name', 'docf'). Nothing opened it and no handler read it. The plain text page keeps its text, Debug Info and Document Pages buttons. Co-Authored-By: Claude Sonnet 5.5 --- test_integration.py | 2 ++ web/plain.html | 47 --------------------------------------------- 2 files changed, 2 insertions(+), 47 deletions(-) diff --git a/test_integration.py b/test_integration.py index 123b8f6..9d23dcf 100644 --- a/test_integration.py +++ b/test_integration.py @@ -235,6 +235,8 @@ def test_http_endpoints(self): r, body = self.get('/plaintext?name=' + name) self.assertEqual(2, body.count(b'
    Plain Text
     		 Document Pages		
     	% endif
     	

    - -
    - - - - -
    From 0a79b0352500dddfc66bd547598e705ed8df5e6a Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 19:58:55 +0000 Subject: [PATCH 26/31] A printing failure no longer loses a job, and the tests never print CI was failing: delivery notes are auto-printed, lpr does not exist on the GitHub runner or in the python:3.11-slim image, and the FileNotFoundError escaped saveJob before the job was added to the in-memory list, so the job silently vanished (the Docker build runs the same tests and failed the same way). * saveJob: a failure in autoPrint is logged and the job is still registered. It is already saved to disk, and this is a real fault outside CI too: any lpr failure hid the job from the web interface until a restart. * tests: main.printFile is mocked for the integration tests, so they cannot print (on a machine with lpr and a printer called HP_TONY, the default auto_printer, they would have). New tests check that delivery notes are auto-printed and that a printing failure does not lose the job. Co-Authored-By: Claude Sonnet 5.5 --- main.py | 7 ++++++- test_integration.py | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 7368f05..0484d6c 100755 --- a/main.py +++ b/main.py @@ -68,7 +68,12 @@ def saveJob(queue, local, remote, control, data): pickle.dump(d, f, protocol=PICKLE_PROTOCOL) cleanJob(d) - autoPrint(d) + try: + autoPrint(d) + except Exception: + # a printing problem (no lpr, no CUPS...) must not lose the job: it is already saved to disk, and + # not registering it here would hide it from the web interface until the next restart + traceback.print_exc(file=sys.stdout) jobs.insert(0, d) if len(jobs) > loadQty: jobs.pop() diff --git a/test_integration.py b/test_integration.py index 9d23dcf..b934081 100644 --- a/test_integration.py +++ b/test_integration.py @@ -14,6 +14,7 @@ import threading import time import unittest +from unittest import mock import main import mailer @@ -91,6 +92,10 @@ def setUpClass(cls): cls.old_user_dir, emailtemplates.USER_DIR = emailtemplates.USER_DIR, os.path.join(cls.home, 'templates') for x in [main.jobdir, main.pdfdir]: os.makedirs(x, exist_ok=True) + # Nothing in these tests may print. Delivery notes and pick lists are auto-printed (defaults.cfg), which + # would run lpr: on a machine without CUPS that fails, and on one with a printer called HP_TONY it would print. + cls.print_patch = mock.patch.object(main, 'printFile') + cls.printed = cls.print_patch.start() cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0) cls.http = ToyHttpServer(ip='127.0.0.1', port=0, pathhandlers=main.path_handlers, webroot=main.web_dir) cls.lpd_port = cls.lpd.socket.getsockname()[1] @@ -104,6 +109,7 @@ def tearDownClass(cls): cls.thread.join() cls.lpd.close() cls.http.close() + cls.print_patch.stop() emailtemplates.USER_DIR = cls.old_user_dir shutil.rmtree(cls.home, ignore_errors=True) @@ -137,6 +143,7 @@ def add_contact(self, account, email, name): self.post_redirect('/settings/email', account=account, email=email, contact=name) def setUp(self): + self.printed.reset_mock() main.jobs.clear() main.email_addresses.clear() shutil.rmtree(emailtemplates.USER_DIR, ignore_errors=True) @@ -714,6 +721,36 @@ def test_the_template_editor_ignores_actions_that_arrive_by_get(self): self.assertEqual(200, r.status) self.assertIn(b'__import__', body) + def test_delivery_notes_are_auto_printed(self): + j = self.send_invoice('Delvnote') + self.assertEqual(main.config.get('Robot', '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.assertTrue(path.startswith(main.pdfdir) and path.endswith('.pdf'), path) + # an invoice is not an auto-print type + self.printed.reset_mock() + self.send_invoice('Invoice') + self.printed.assert_not_called() + + def test_a_printing_failure_does_not_lose_the_job(self): + # without lpr (a container, a CI runner) or with CUPS down, printing raises; the job must still be there + self.printed.side_effect = FileNotFoundError(2, 'No such file or directory', 'lpr') + try: + j = self.send_invoice('Delvnote') + finally: + self.printed.side_effect = None + self.assertEqual(1, len(main.jobs)) + self.assertEqual(j['name'], main.jobs[0]['name']) + self.printed.assert_called_once() + r, body = self.get('/pdf?name=' + j['name']) # it can be opened, emailed and so on + self.assertEqual(200, r.status) + self.assertNotIn(b'Mako Runtime Error', body) + r, body = self.get('/recent?fmt=json') + self.assertIn(j['name'], body.decode()) + with open(os.path.join(main.jobdir, j['name'][4:10], j['name']), 'rb') as f: # and it was saved to disk + self.assertTrue(f.read(2) == b'\x80\x02') + def test_pdf_page_for_a_job_that_is_not_loaded_is_a_message_not_an_error(self): self.send_invoice() r, body = self.get('/pdf?name=job-19990101-000000') From 6d6a0f52c1ed80c1c83cc9d8f8ea14e6802ebf38 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 21:29:45 +0000 Subject: [PATCH 27/31] Printers page shows the CUPS state and whether auto-printing can work One lpstat -t (C locale, 5s timeout, cached 10s) is parsed into printers and waiting jobs, with device URI credentials masked. The page says which document types are auto-printed and on which queue, gives a plain-English verdict (scheduler down, queue missing, disabled or not accepting, jobs waiting over an hour) and lists the waiting jobs with stale ones highlighted. Read-only; tests never run the machine's lpstat. The print menu on the job page now lists the same CUPS queues. getPrinters() used to return a made-up 'default' on anything but linux, which lpr rejects; it is empty if CUPS can't be reached. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP --- README.md | 1 + main.py | 14 +- printing.py | 23 +-- printstatus.py | 336 ++++++++++++++++++++++++++++++++++++++++++++ test_integration.py | 36 +++++ web/printers.html | 85 ++++++++++- 6 files changed, 471 insertions(+), 24 deletions(-) create mode 100644 printstatus.py diff --git a/README.md b/README.md index 54b953e..646f084 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ The following will checkout the source code, build a docker image and start an i * `docparser` recognise and parse some plain-text formats from 1990 to JSON * `stationary.py` format JSON to nice PDF files * `printing.py` Linux printing with CUPS via. command line +* `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 A GET never changes anything: sending an email, printing, editing the address book and saving or reverting a template are POSTs, and their handlers return `httpserver.Redirect(...)` (a 303) to a page that is safe to refresh, diff --git a/main.py b/main.py index 0484d6c..8558d85 100755 --- a/main.py +++ b/main.py @@ -13,6 +13,7 @@ from docparser import DocParser from stationary import DocFormatter from printing import getPrinters, printFile +import printstatus import sys, pickle import html @@ -272,7 +273,18 @@ def job(query_string=dict(), resp=None): return json.dumps(output, indent=3), 'text/json' def printers(query_string='', resp=None): - return ( template_lookup.get_template("/printers.html").render(printers=getPrinters()), 'text/html') + """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') + try: + st = printstatus.status() + error = None + verdict = printstatus.assess(st, auto_printer) + except printstatus.LpstatError as e: + st, error, verdict = None, str(e), None + return ( template_lookup.get_template("/printers.html").render(st=st, error=error, verdict=verdict, + auto_types=auto_types, auto_printer=auto_printer, humanise=printstatus.humanise, + now=datetime.now(), stale=printstatus.STALE_AFTER), 'text/html') # The Sent Items page only shows this many of the most recent emails, however long the history is: the # history goes back years and the whole of it makes a page of many MB. diff --git a/printing.py b/printing.py index 9d799fe..d6533c3 100644 --- a/printing.py +++ b/printing.py @@ -1,24 +1,15 @@ #!/usr/bin/env python3 -import sys import subprocess - -printers = [] +import printstatus def getPrinters(): - global printers - if not sys.platform.startswith("linux"): - return ['default'] - if len(printers) > 0: return printers + """Names of the CUPS queues, as the Printers page sees them (same lpstat call, so the two always agree). + Empty if CUPS can't be asked, so the print menu is empty rather than offering a queue that doesn't exist.""" try: - process = subprocess.Popen(["lpstat", "-a"], stdout=subprocess.PIPE, universal_newlines=True) - result = process.communicate()[0].strip() - # KONICA_bizhub_192.168.12.10 accepting requests since Sun 16 Dec 2012 07:43:59 PM GMT - print(result) - printers = [x.split(' ')[0] for x in result.split('\n') if x.strip()] - print('[print] printers=%s' % repr(printers)) - except OSError as e: - print('[print] %s' % repr(e)) - return printers + return [p.name for p in printstatus.status().printers] + except printstatus.LpstatError as e: + print('[print] %s' % e) + return [] def printFile(file, printer): cmd = ["lpr","-P", printer, file] diff --git a/printstatus.py b/printstatus.py new file mode 100644 index 0000000..a27994b --- /dev/null +++ b/printstatus.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +# Read-only view of CUPS for the Printers page: one `lpstat -t` call, parsed, plus a plain-English verdict on +# whether automatic printing can be expected to work. +# +# lpstat only produces text meant for people, and in the locale of the server, so we ask for the C locale +# ("Wed Sep 9 15:02:14 2026", no timezone). It says nothing about whether a job came out of the printer: +# a job leaves the queue when CUPS has handed it to the device, and a queue stuck "Connecting to printer..." +# is the only sign of trouble. So this page can show a stuck queue, but never prove a page was printed. +import os +import re +import subprocess +import time +from collections import namedtuple +from datetime import datetime, timedelta + +LPSTAT_TIMEOUT = 5 +CACHE_SECONDS = 10 +STALE_AFTER = timedelta(hours=1) # a job waiting longer than this on a working printer is not "about to print" + +Printer = namedtuple('Printer', 'name device state job since accepting accepting_since message reason reject_reason') +Job = namedtuple('Job', 'id printer user size submitted') +Status = namedtuple('Status', 'scheduler default printers jobs fetched') + + +class LpstatError(Exception): + pass + + +def run_lpstat(): + """Text of `lpstat -t` in the C locale, or LpstatError if it can't be had.""" + env = dict(os.environ, LC_ALL='C', LANG='C') + try: + p = subprocess.run(['lpstat', '-t'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, + timeout=LPSTAT_TIMEOUT, universal_newlines=True) + except FileNotFoundError: + raise LpstatError('lpstat is not installed on this machine') + except subprocess.TimeoutExpired: + raise LpstatError('lpstat did not answer within %d seconds' % LPSTAT_TIMEOUT) + except OSError as e: + raise LpstatError('lpstat could not be run: %s' % e) + if p.returncode != 0: + # cupsd stopped: "lpstat: Bad file descriptor" / "Unable to connect to server" + raise LpstatError((p.stderr or p.stdout).strip() or 'lpstat failed (exit %d)' % p.returncode) + return p.stdout + + +def mask_uri(uri): + """A device URI can carry a password (ipp://user:secret@host/...): never show that part.""" + return re.sub(r'^([a-z][a-z0-9+.-]*://)[^/@]*@', r'\1', uri.strip(), flags=re.I) + + +def parse_date(text): + """'Wed Sep 9 15:02:14 2026' (C locale) as a naive local datetime, else None.""" + text = ' '.join(text.split()) + for fmt in ('%a %b %d %H:%M:%S %Y', '%a %d %b %Y %I:%M:%S %p %Z', '%a %d %b %Y %H:%M:%S %Z'): + try: + return datetime.strptime(text, fmt) + except ValueError: + continue + return None + + +_SINCE = r'(?P.*?)(?:\s+-)?' +_ACCEPTING = re.compile(r'^(?P\S+) (?Paccepting|not accepting) requests since ' + _SINCE + r'$') +_DEVICE = re.compile(r'^device for (?P[^:]+): (?P.*)$') +_PRINTER = re.compile(r'^printer (?P\S+) (?:(?Pis idle)|now printing (?P\S+?)|(?Pdisabled))\.?\s+' + r'(?:enabled )?since ' + _SINCE + r'$') +_JOB = re.compile(r'^(?P\S+)-(?P\d+)\s+(?P\S+)\s+(?P\d+)\s+(?P\S.*)$') + + +def parse(text, fetched=None): + """Parse `lpstat -t` output. Lines we don't recognise are ignored rather than fatal.""" + scheduler = None + default = None + devices = {} + accepting = {} + states = {} + order = [] + jobs = [] + last = None # the printer record that following tab-indented lines belong to + for line in text.splitlines(): + if not line.strip(): + continue + if line[0] in ' \t': + if last is not None and last in states: + states[last]['text'] = line.strip() + continue + last = None + if line.startswith('scheduler is '): + scheduler = line[len('scheduler is '):].strip().rstrip('.') + elif line.startswith('system default destination: '): + default = line.split(': ', 1)[1].strip() + elif line.startswith('no system default destination'): + default = None + elif _DEVICE.match(line): + m = _DEVICE.match(line) + devices[m.group('name')] = mask_uri(m.group('uri')) + elif _ACCEPTING.match(line): + m = _ACCEPTING.match(line) + accepting[m.group('name')] = (m.group('ok') == 'accepting', parse_date(m.group('since'))) + if m.group('name') not in order: + order.append(m.group('name')) + last = ('acc', m.group('name')) + states[last] = {} + elif _PRINTER.match(line): + m = _PRINTER.match(line) + state = 'disabled' if m.group('disabled') else 'idle' if m.group('idle') else 'printing' + states[m.group('name')] = {'state': state, 'job': m.group('job'), 'since': parse_date(m.group('since'))} + if m.group('name') not in order: + order.append(m.group('name')) + last = m.group('name') + elif _JOB.match(line): + m = _JOB.match(line) + jobs.append(Job(m.group('printer') + '-' + m.group('id'), m.group('printer'), m.group('user'), + int(m.group('size')), parse_date(m.group('date')))) + printers = [] + for name in order: + st = states.get(name, {}) + acc = accepting.get(name, (None, None)) + # the indented line after "not accepting" is why; after "disabled" it is why; otherwise it is a status message + why = states.get(('acc', name), {}).get('text') if acc[0] is False else None + text_ = st.get('text') + state = st.get('state', 'unknown') + printers.append(Printer(name, devices.get(name), state, st.get('job'), st.get('since'), acc[0], acc[1], + text_ if state != 'disabled' else None, text_ if state == 'disabled' else None, why)) + return Status(scheduler, default, printers, jobs, fetched or datetime.now()) + + +_cache = {'when': 0, 'value': None} + + +def reset_cache(): + _cache['when'] = 0 + _cache['value'] = None + + +def status(): + """The current Status (cached a few seconds so a refreshing page can't hammer cupsd), or LpstatError.""" + now = time.time() + if _cache['value'] is None or now - _cache['when'] > CACHE_SECONDS: + _cache['value'] = parse(run_lpstat()) + _cache['when'] = now + return _cache['value'] + + +def humanise(delta): + secs = int(delta.total_seconds()) + if secs < 0: + return 'in the future' + if secs < 90: + return 'just now' if secs < 10 else '%d seconds' % secs + for unit, size in (('year', 365 * 86400), ('month', 30 * 86400), ('day', 86400), ('hour', 3600), ('minute', 60)): + if secs >= size * (1.5 if unit in ('hour', 'minute') else 1): + n = secs // size + return '%d %s%s' % (n, unit, '' if n == 1 else 's') + return '%d minutes' % (secs // 60) + + +Verdict = namedtuple('Verdict', 'level problems') # level: ok | warning | error + + +def assess(st, printer_name, now=None): + """Can automatic printing to `printer_name` be expected to work? Plain-English problems, worst first.""" + now = now or st.fetched + errors, warnings = [], [] + if st.scheduler != 'running': + errors.append('The CUPS scheduler is not running, so nothing can print.') + p = next((x for x in st.printers if x.name == printer_name), None) + if p is None: + errors.append('CUPS has no printer called %s, so automatic printing fails.' % printer_name) + else: + if p.state == 'disabled': + errors.append('%s is disabled%s.' % (p.name, ': ' + p.reason if p.reason else '')) + if p.accepting is False: + errors.append('%s is not accepting jobs%s.' % (p.name, ': ' + p.reject_reason if p.reject_reason else '')) + waiting = [j for j in st.jobs if j.printer == p.name] + old = [j for j in waiting if j.submitted and now - j.submitted > STALE_AFTER] + if old: + oldest = min(j.submitted for j in old) + warnings.append('%d job%s for %s %s been waiting for %s or more, so this printer may be stuck.' % ( + len(old), '' if len(old) == 1 else 's', p.name, 'has' if len(old) == 1 else 'have', humanise(now - oldest))) + if errors: + return Verdict('error', errors + warnings) + if warnings: + return Verdict('warning', warnings) + return Verdict('ok', []) + + +import unittest + +SAMPLE = """scheduler is running +no system default destination +device for OFFICE_MFP: lpd://192.0.2.100/MF8200C +device for DESK_LASER: socket://192.0.2.212 +device for HALL_COPIER_192.0.2.10: socket://192.0.2.10 +OFFICE_MFP accepting requests since Wed Sep 9 15:02:14 2026 +DESK_LASER accepting requests since Wed Oct 25 12:01:17 2023 +HALL_COPIER_192.0.2.10 accepting requests since Thu Nov 19 16:33:41 2026 +printer OFFICE_MFP now printing OFFICE_MFP-41070. enabled since Wed Sep 9 15:02:14 2026 +\tConnecting to printer... +printer DESK_LASER is idle. enabled since Wed Oct 25 12:01:17 2023 +printer HALL_COPIER_192.0.2.10 is idle. enabled since Thu Nov 19 16:33:41 2026 +\tReady to print. +OFFICE_MFP-41070 printerface 91136 Wed Jun 29 13:27:57 2016 +OFFICE_MFP-41071 printerface 5120 Wed Jun 29 13:28:27 2016 +DESK_LASER-56672 printerface 64512 Tue May 30 09:14:10 2017 +""" + +# The two failure shapes below were written from CUPS 1.4's lpstat.c, not captured: no queue on our server has been +# disabled or stopped from accepting jobs. +BROKEN = """scheduler is running +system default destination: DESK_LASER +device for DESK_LASER: ipp://admin:s3cret@192.0.2.212/ipp/print +DESK_LASER not accepting requests since Thu Nov 19 10:00:00 2026 - +\tRejecting Jobs +printer DESK_LASER disabled since Thu Nov 19 10:00:00 2026 - +\tPaused +""" + +NOW = datetime(2026, 11, 19, 17, 0, 0) + + +class TestParse(unittest.TestCase): + def setUp(self): + self.st = parse(SAMPLE, NOW) + + def test_scheduler_and_default(self): + self.assertEqual(self.st.scheduler, 'running') + self.assertIsNone(self.st.default) + self.assertEqual(parse(BROKEN, NOW).default, 'DESK_LASER') + + def test_printers_in_order(self): + self.assertEqual([p.name for p in self.st.printers], ['OFFICE_MFP', 'DESK_LASER', 'HALL_COPIER_192.0.2.10']) + hall = self.st.printers[2] + self.assertEqual((hall.state, hall.accepting, hall.message, hall.device), ('idle', True, 'Ready to print.', 'socket://192.0.2.10')) + self.assertEqual(hall.since, datetime(2026, 11, 19, 16, 33, 41)) + + def test_busy_printer_has_its_job_and_message(self): + p = self.st.printers[0] + self.assertEqual((p.state, p.job, p.message), ('printing', 'OFFICE_MFP-41070', 'Connecting to printer...')) + + def test_jobs(self): + self.assertEqual([j.id for j in self.st.jobs], ['OFFICE_MFP-41070', 'OFFICE_MFP-41071', 'DESK_LASER-56672']) + self.assertEqual(self.st.jobs[0].size, 91136) + self.assertEqual(self.st.jobs[2].submitted, datetime(2017, 5, 30, 9, 14, 10)) + + def test_stopped_printer_gives_reasons(self): + p = parse(BROKEN, NOW).printers[0] + self.assertEqual((p.state, p.accepting, p.reason), ('disabled', False, 'Paused')) + + def test_not_accepting_reason(self): + text = BROKEN.replace('printer DESK_LASER disabled since Thu Nov 19 10:00:00 2026 -\n\tPaused\n', + 'printer DESK_LASER is idle. enabled since Thu Nov 19 10:00:00 2026\n') + p = parse(text, NOW).printers[0] + self.assertEqual((p.state, p.accepting, p.reject_reason), ('idle', False, 'Rejecting Jobs')) + + def test_credentials_never_shown(self): + p = parse(BROKEN, NOW).printers[0] + self.assertEqual(p.device, 'ipp://192.0.2.212/ipp/print') + self.assertNotIn('s3cret', repr(p)) + + def test_junk_is_ignored(self): + st = parse('\nwhat is this\n' + SAMPLE, NOW) + self.assertEqual(len(st.printers), 3) + + def test_dates(self): + self.assertEqual(parse_date('Wed Sep 9 15:02:14 2026'), datetime(2026, 9, 9, 15, 2, 14)) + self.assertEqual(parse_date('Wed 09 Sep 2026 03:02:14 PM BST'), datetime(2026, 9, 9, 15, 2, 14)) + self.assertIsNone(parse_date('yesterday')) + + +class TestAssess(unittest.TestCase): + def test_stuck_queue_is_a_warning_for_that_printer_only(self): + st = parse(SAMPLE, NOW) + self.assertEqual(assess(st, 'HALL_COPIER_192.0.2.10').level, 'ok') + v = assess(st, 'OFFICE_MFP') + self.assertEqual(v.level, 'warning') + self.assertIn('2 jobs', v.problems[0]) + + def test_missing_printer(self): + v = assess(parse(SAMPLE, NOW), 'NOPE') + self.assertEqual(v.level, 'error') + self.assertIn('no printer called NOPE', v.problems[0]) + + def test_disabled_and_not_accepting(self): + v = assess(parse(BROKEN, NOW), 'DESK_LASER') + self.assertEqual(v.level, 'error') + self.assertEqual(len(v.problems), 2) + self.assertTrue(any('Paused' in x for x in v.problems) and any('Rejecting Jobs' in x for x in v.problems)) + + def test_scheduler_down(self): + self.assertEqual(assess(parse(SAMPLE.replace('is running', 'is not running'), NOW), 'DESK_LASER').level, 'error') + + def test_recent_jobs_are_fine(self): + st = parse(SAMPLE.replace('Wed Jun 29 13:27:57 2016', 'Thu Nov 19 16:50:00 2026') + .replace('Wed Jun 29 13:28:27 2016', 'Thu Nov 19 16:51:00 2026'), NOW) + self.assertEqual(assess(st, 'OFFICE_MFP').level, 'ok') + + def test_humanise(self): + self.assertEqual(humanise(timedelta(seconds=3)), 'just now') + self.assertEqual(humanise(timedelta(minutes=5)), '5 minutes') + self.assertEqual(humanise(timedelta(hours=3)), '3 hours') + self.assertEqual(humanise(timedelta(days=1)), '1 day') + self.assertEqual(humanise(timedelta(days=800)), '2 years') + + +class TestRun(unittest.TestCase): + def tearDown(self): + reset_cache() + + def test_missing_lpstat_is_an_error_not_a_crash(self): + import unittest.mock as mock + with mock.patch('subprocess.run', side_effect=FileNotFoundError()): + with self.assertRaises(LpstatError): + run_lpstat() + + def test_cupsd_down(self): + import unittest.mock as mock + r = subprocess.CompletedProcess([], 1, '', 'lpstat: Bad file descriptor\n') + with mock.patch('subprocess.run', return_value=r): + with self.assertRaisesRegex(LpstatError, 'Bad file descriptor'): + run_lpstat() + + def test_cached_between_calls(self): + import unittest.mock as mock + with mock.patch(__name__ + '.run_lpstat', return_value=SAMPLE) as run: + status() + status() + self.assertEqual(run.call_count, 1) + reset_cache() + status() + self.assertEqual(run.call_count, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/test_integration.py b/test_integration.py index b934081..b72a29e 100644 --- a/test_integration.py +++ b/test_integration.py @@ -18,6 +18,7 @@ import main import mailer +import printstatus import emailtemplates from stationary import DocFormatter from lpdserver import LpdServer @@ -96,6 +97,9 @@ def setUpClass(cls): # would run lpr: on a machine without CUPS that fails, and on one with a printer called HP_TONY it would print. cls.print_patch = mock.patch.object(main, 'printFile') cls.printed = cls.print_patch.start() + # likewise the Printers page: lpstat is only ever the canned text, never the machine's own CUPS + cls.lpstat_patch = mock.patch.object(printstatus, 'run_lpstat', return_value=printstatus.SAMPLE) + cls.lpstat_patch.start() cls.lpd = LpdServer(main.saveJob, ip='127.0.0.1', port=0) cls.http = ToyHttpServer(ip='127.0.0.1', port=0, pathhandlers=main.path_handlers, webroot=main.web_dir) cls.lpd_port = cls.lpd.socket.getsockname()[1] @@ -110,9 +114,38 @@ def tearDownClass(cls): cls.lpd.close() cls.http.close() cls.print_patch.stop() + cls.lpstat_patch.stop() emailtemplates.USER_DIR = cls.old_user_dir shutil.rmtree(cls.home, ignore_errors=True) + def test_printers_page(self): + printstatus.reset_cache() + old = main.config.get('Robot', 'auto_printer') + try: + main.config.set('Robot', 'auto_printer', 'DESK_LASER') + r, body = self.get('/printers') + self.assertEqual(r.status, 200) + text = body.decode() + for expected in ['OFFICE_MFP', 'HALL_COPIER_192.0.2.10', 'Connecting to printer...', 'socket://192.0.2.10', 'OFFICE_MFP-41071']: + 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') + printstatus.reset_cache() + self.assertIn('no printer called NOPE', self.get('/printers')[1].decode()) + finally: + main.config.set('Robot', 'auto_printer', old) + printstatus.reset_cache() + + def test_printers_page_without_cups(self): + printstatus.reset_cache() + with mock.patch.object(printstatus, 'run_lpstat', side_effect=printstatus.LpstatError('cupsd is ')): + r, body = self.get('/printers') + self.assertEqual(r.status, 200) + self.assertIn("Can't read the printer status", body.decode()) + self.assertIn('cupsd is <down>', body.decode()) + printstatus.reset_cache() + def get(self, path, headers=None): conn = http.client.HTTPConnection('127.0.0.1', self.http_port, timeout=10) conn.request('GET', path, headers=headers or {}) @@ -673,6 +706,9 @@ def test_printing_is_a_post_that_redirects(self): r, body = self.get('/pdf?name=%s&key=ACC001' % j['name']) self.assertIn(b'
    <%block name="title">- Printers +<% + def ago(when): + return humanise(now - when) + ' ago' if when else 'unknown' + def when_s(when): + return when.strftime('%d %b %Y %H:%M') if when else '' + def size_s(n): + return '%.0f KB' % (n / 1024.0) if n >= 1024 else '%d B' % n + LEVEL = {'ok': ('success', 'Automatic printing looks healthy'), 'warning': ('warning', 'Automatic printing may not be working'), + 'error': ('error', 'Automatic printing will fail')} + STATE = {'idle': 'label-success', 'printing': 'label-info', 'disabled': 'label-important'} +%>

    Printers

    - - - % for p in printers: - - - +

    Automatic printing

    +

    Documents of type + % for t in auto_types: + ${t | h}${',' if not loop.last else ''} + % endfor + are printed on ${auto_printer | h} as soon as they arrive. This is set by auto_types and + auto_printer under [Robot] in ~/printerface/email.cfg.

    + + % if error: +
    Can't read the printer status. ${error | h}
    + % else: + <% cls, headline = LEVEL[verdict.level] %> +
    + ${headline}. + % if verdict.problems: +
      + % for problem in verdict.problems: +
    • ${problem | h}
    • + % endfor +
    + % else: + CUPS is running and ${auto_printer | h} is ready. + % endif +
    + % endif + + % if st: +

    CUPS printers

    +
    Printer
    ${p}
    + + % for p in st.printers: + <% waiting = [j for j in st.jobs if j.printer == p.name] %> + + + + + + + + + + % endfor +
    PrinterStateAccepting jobsSinceWaitingMessageDevice
    ${p.name | h} + % if p.name == auto_printer: + auto-print + % endif + % if p.name == st.default: + default + % endif + ${p.state | h}${'yes' if p.accepting else 'NO' if p.accepting is False else '?'}${(': ' + p.reject_reason) if p.reject_reason else '' | h}${ago(p.since) | h}${len(waiting) or ''}${(p.reason or p.message or '') | h}${(p.device or '') | h}
    +

    For an idle printer, Since is when CUPS last changed its state, roughly when it last printed. Waiting is not a record of paper + that came out: CUPS forgets a job once it has been handed to the printer.

    + + % if st.jobs: +

    Jobs waiting in CUPS

    + + + % for j in sorted(st.jobs, key=lambda j: j.submitted or now, reverse=True): + + + + % endfor
    JobOwnerSizeSubmittedWaiting
    ${j.id | h}${j.user | h}${size_s(j.size)}${when_s(j.submitted) | h}${ago(j.submitted).replace(' ago', '') | h}
    + % else: +

    No jobs are waiting in CUPS.

    + % endif +

    Fetched ${st.fetched.strftime('%H:%M:%S') | h} – refresh

    + % endif

    To add or change printers use CUPS Administration From 2a416de86c4a9fa2e3b9d01280a6f2f25c28b665 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Thu, 19 Nov 2026 21:49:23 +0000 Subject: [PATCH 28/31] Printing uses lp and records the CUPS request id against the job and document lp reports the queue-and-number a job gets in CUPS, which is the name lpstat knows it by. printFile now runs lp with a timeout, records job, key, printer and request id (or the error) in printer.pickle, a side file like mailer.pickle, and raises if CUPS refused the job, so a failed print is no longer reported as sent. The history keeps the newest result_count records and is flushed from the main loop only when changed. The job page lists what was printed from it, as it does for sent emails. Auto-print carries on with the remaining documents if one fails. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP --- README.md | 2 +- main.py | 18 ++++- printing.py | 177 ++++++++++++++++++++++++++++++++++++++++++-- test_integration.py | 26 +++++++ web/pdf.html | 16 ++++ 5 files changed, 227 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 646f084..ba00282 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ The following will checkout the source code, build a docker image and start an i * `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 -* `printing.py` Linux printing with CUPS via. command line +* `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 `result_count` like the sent emails, and listed on the job page. The file is written from the main loop only when something changed * `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 A GET never changes anything: sending an email, printing, editing the address book and saving or reverting a diff --git a/main.py b/main.py index 8558d85..62b5531 100755 --- a/main.py +++ b/main.py @@ -13,6 +13,7 @@ from docparser import DocParser from stationary import DocFormatter from printing import getPrinters, printFile +import printing import printstatus import sys, pickle @@ -87,8 +88,12 @@ def autoPrint(job): for (groupnum, gname) in enumerate(job['groupkey']): for (dockey, doc) in job['groupfiles'].items(): if doc: - printFile(pdfdir + doc, printer ) - print( 'auto printing: Document %s sent to printer %s' % (doc, printer)) + try: + printFile(pdfdir + doc, printer ) + print( 'auto printing: Document %s sent to printer %s' % (doc, printer)) + except Exception as e: + # recorded in the print history; carry on with the other documents + print( 'auto printing: Document %s NOT sent to printer %s: %s' % (doc, printer, e)) def saveEmails(): with open(email_pickle, 'wb') as f: @@ -338,8 +343,9 @@ def printfn(query_string='', postreq=None, resp=None): printFile(pdfdir + docf, printer) key = postreq.get('key', [next(iter(job['groupfiles']))[0]])[0] return Redirect('/pdf?' + urllib.parse.urlencode({'name': job['name'], 'key': key, 'printed': printer})) - except Exception: + except Exception as e: traceback.print_exc(file=sys.stdout) + return doMessage(title='Printing', message='The document was not printed: %s
    Source: %s sent to printer %s
    ' % (html.escape(str(e)), html.escape(str(docf)), html.escape(printer))) 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(): @@ -481,6 +487,8 @@ def pdf(query_string=dict(), postreq=None, resp=None): # emails made from this job that are still in the sent history, newest first sent_from_this_job = mailer.sent_from_job(mailqueue.results, job['name']) + # and what was sent to a printer from it, with the CUPS request ids + printed_from_this_job = printing.printlog.for_job(job['name']) # what the editor's preview filter should be set to so that it shows this document if template_kind == emailtemplates.DEFAULT: @@ -491,7 +499,7 @@ def pdf(query_string=dict(), postreq=None, resp=None): template_docnum = pages[0].get('doc_num', '').strip() return ( template_lookup.get_template("/pdf.html").render(printers=getPrinters(), job=job, key=key, email_templ=email_body_default, email_subject_default=email_subject_default, ticked=typed['ticked'] if typed else None, - template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, + template_kind=template_kind, template_warning=template_warning, template_docnum=template_docnum, sent_from_this_job=sent_from_this_job, printed_from_this_job=printed_from_this_job, email_body_url='/email_body?' + urllib.parse.urlencode({'name': job['name'], 'key': key}), email_dest=email_dest, email_outcome=email_outcome, email_error=email_error), 'text/html') @@ -626,10 +634,12 @@ def htmlcol(rgb): while True: asyncore.loop(timeout=1, count=10) print('[control] poll %s' % str(datetime.now())) + printing.printlog.flush() sys.stdout.flush() except KeyboardInterrupt: print("Crtl+C pressed. Shutting down.") + printing.printlog.flush() except: print("Terminating: Unexpected error: %s" % sys.exc_info()[0]) sys.stdout.flush() diff --git a/printing.py b/printing.py index d6533c3..66ed047 100644 --- a/printing.py +++ b/printing.py @@ -1,6 +1,72 @@ #!/usr/bin/env python3 +import datetime +import os +import pickle +import re import subprocess +import traceback +import unittest +import unittest.mock as mock + +import mailer import printstatus +from settings import config, HOME +from textutil import PICKLE_PROTOCOL + +PRINT_TIMEOUT = 30 +pickle_file = os.path.join(HOME, 'printer.pickle') + + +class PrintError(Exception): + pass + + +class PrintLog(object): + """What was sent to CUPS, newest first, one record per document: the job and key it came from, the printer, and + the CUPS request id (the name lpstat knows the job by) or the error. Kept in a side pickle, like the sent + emails, so the job pickles are never rewritten. The newest `limit` records are kept (the same setting as the + email history) and the file is only written, by flush(), when something changed.""" + + def __init__(self, path=None, limit=None): + self.path = path + self.limit = limit if limit is not None else config.getint('Gmail', 'result_count') + self.records = [] + self.dirty = False + if path: + try: + with open(path, 'rb') as f: + self.records = pickle.load(f) + except FileNotFoundError: + pass + except Exception: + traceback.print_exc() + del self.records[self.limit:] + + def add(self, record): + self.records.insert(0, record) + del self.records[self.limit:] + self.dirty = True + + def for_job(self, job_name): + """The records made from this job, newest first.""" + return [r for r in self.records if r.get('job') == job_name] + + def flush(self): + """Write the history if it changed. Never raises: a full disk mustn't stop the server.""" + if not self.dirty or not self.path: + return + try: + tmp = self.path + '.tmp' + with open(tmp, 'wb') as f: + pickle.dump(self.records, f, protocol=PICKLE_PROTOCOL) + os.replace(tmp, self.path) + self.dirty = False + except Exception: + traceback.print_exc() + + +printlog = PrintLog(pickle_file) + def getPrinters(): """Names of the CUPS queues, as the Printers page sees them (same lpstat call, so the two always agree). @@ -12,13 +78,110 @@ def getPrinters(): return [] def printFile(file, printer): - cmd = ["lpr","-P", printer, file] - print("[print] printer=%s file=%s cmd=%s" %(printer, file, repr(cmd) )) - process = subprocess.Popen(cmd, stdout=subprocess.PIPE) - results = process.communicate() - results = (None,None) - print("[print] printer=%s file=%s cmd=%s result=%s" %(printer, file, repr(cmd), repr(results))) + """Send a PDF to a CUPS queue with lp, record the outcome in printlog and return the record. lp reports the + job's CUPS request id (KONICA_bizhub_192.168.12.10-12345), which is how the job shows up in lpstat. + Raises PrintError, after recording it, if the job was not accepted.""" + cmd = ['lp', '-d', printer, file] + ref = mailer.job_ref(file) + record = {'job': ref[0] if ref else None, 'key': ref[1] if ref else None, 'file': file, 'printer': printer, + 'request_id': None, 'added': datetime.datetime.now(), 'error': None} + try: + p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=PRINT_TIMEOUT, + env=dict(os.environ, LC_ALL='C', LANG='C'), universal_newlines=True) + m = re.search(r'request id is (\S+)', p.stdout) + record['request_id'] = m.group(1) if m else None + if p.returncode != 0: + record['error'] = (p.stderr or p.stdout).strip() or 'lp failed (exit %d)' % p.returncode + except FileNotFoundError: + record['error'] = 'lp is not installed on this machine' + except subprocess.TimeoutExpired: + record['error'] = 'lp did not finish within %d seconds' % PRINT_TIMEOUT + except OSError as e: + record['error'] = 'lp could not be run: %s' % e + print("[print] printer=%s file=%s request=%s error=%s" % (printer, file, record['request_id'], record['error'])) + printlog.add(record) + if record['error']: + raise PrintError(record['error']) + return record + + +class TestPrintFile(unittest.TestCase): + PDF = '/p/2026/ACC001/job-20261119-101010-ACC001.pdf' + + def setUp(self): + self.log = PrintLog(None, limit=3) + patch = mock.patch.object(__import__(__name__), 'printlog', self.log) + patch.start() + self.addCleanup(patch.stop) + + def lp(self, stdout='', stderr='', code=0): + return mock.patch('subprocess.run', return_value=subprocess.CompletedProcess([], code, stdout, stderr)) + + def test_records_the_request_id_against_job_and_key(self): + with self.lp('request id is KONICA_bizhub_192.168.12.10-12345 (1 file(s))\n') as run: + rec = printFile(self.PDF, 'KONICA_bizhub_192.168.12.10') + self.assertEqual(['lp', '-d', 'KONICA_bizhub_192.168.12.10', self.PDF], run.call_args[0][0]) + self.assertEqual('KONICA_bizhub_192.168.12.10-12345', rec['request_id']) + self.assertEqual(('job-20261119-101010', 'ACC001', None), (rec['job'], rec['key'], rec['error'])) + self.assertEqual([rec], self.log.for_job('job-20261119-101010')) + self.assertEqual([], self.log.for_job('job-20000101-000000')) + self.assertTrue(self.log.dirty) + + def test_a_refused_job_is_recorded_and_raised(self): + with self.lp(stderr='lp: The printer or class does not exist.\n', code=1): + with self.assertRaisesRegex(PrintError, 'does not exist'): + printFile(self.PDF, 'default') + self.assertEqual('lp: The printer or class does not exist.', self.log.records[0]['error']) + self.assertIsNone(self.log.records[0]['request_id']) + + def test_no_lp_and_timeouts(self): + with mock.patch('subprocess.run', side_effect=FileNotFoundError()): + with self.assertRaisesRegex(PrintError, 'not installed'): + printFile(self.PDF, 'x') + with mock.patch('subprocess.run', side_effect=subprocess.TimeoutExpired('lp', 30)): + with self.assertRaisesRegex(PrintError, 'did not finish'): + printFile(self.PDF, 'x') + self.assertEqual(2, len(self.log.records)) + + def test_a_file_that_is_not_ours_has_no_job(self): + with self.lp('request id is Q-1 (1 file(s))'): + rec = printFile('/tmp/report.pdf', 'Q') + self.assertEqual((None, None), (rec['job'], rec['key'])) + + def test_keeps_only_the_newest(self): + with self.lp('request id is Q-1 (1 file(s))'): + for _ in range(5): + printFile(self.PDF, 'Q') + self.assertEqual(3, len(self.log.records)) + + +class TestPrintLog(unittest.TestCase): + def test_flush_only_when_dirty_and_survives_a_restart(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, 'printer.pickle') + log = PrintLog(path, limit=2) + log.flush() + self.assertFalse(os.path.exists(path)) # nothing to write yet + for n in range(3): + log.add({'job': 'job-1', 'n': n}) + self.assertTrue(log.dirty) + log.flush() + self.assertFalse(log.dirty) + self.assertEqual([2, 1], [r['n'] for r in PrintLog(path, limit=2).records]) + self.assertEqual([2], [r['n'] for r in PrintLog(path, limit=1).records]) # a smaller limit trims on load + os.remove(path) + log.flush() + self.assertFalse(os.path.exists(path)) # clean: not rewritten + + def test_a_corrupt_file_starts_empty(self): + import tempfile + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, 'printer.pickle') + open(path, 'wb').write(b'garbage') + with mock.patch('traceback.print_exc'): + self.assertEqual([], PrintLog(path, limit=2).records) + if __name__=="__main__": print ('Installed printers: %s' % repr(getPrinters())) - diff --git a/test_integration.py b/test_integration.py index b72a29e..d8e73c5 100644 --- a/test_integration.py +++ b/test_integration.py @@ -14,10 +14,12 @@ import threading import time import unittest +from datetime import datetime from unittest import mock import main import mailer +import printing import printstatus import emailtemplates from stationary import DocFormatter @@ -90,6 +92,7 @@ def setUpClass(cls): main.pdfdir = os.path.join(cls.home, 'data', 'pdf') + os.sep main.formatter = DocFormatter(main.pdfdir) mailer.pickle_file = os.path.join(cls.home, 'mailer.pickle') + cls.old_printlog, printing.printlog = printing.printlog, printing.PrintLog(os.path.join(cls.home, 'printer.pickle')) cls.old_user_dir, emailtemplates.USER_DIR = emailtemplates.USER_DIR, os.path.join(cls.home, 'templates') for x in [main.jobdir, main.pdfdir]: os.makedirs(x, exist_ok=True) @@ -115,6 +118,7 @@ def tearDownClass(cls): cls.http.close() cls.print_patch.stop() cls.lpstat_patch.stop() + printing.printlog = cls.old_printlog emailtemplates.USER_DIR = cls.old_user_dir shutil.rmtree(cls.home, ignore_errors=True) @@ -714,6 +718,28 @@ def test_printing_is_a_post_that_redirects(self): self.assertEqual(200, r.status) printed.assert_called_once() + def test_print_history_is_listed_on_the_job_page(self): + j = self.send_invoice() + self.assertNotIn(b'Printed from this job', self.get('/pdf?name=%s&key=ACC001' % j['name'])[1]) + printing.printlog.add({'job': j['name'], 'key': 'ACC001', 'file': 'x', 'printer': 'OFFICE_MFP', + 'request_id': 'OFFICE_MFP-777', 'added': datetime.now(), 'error': None}) + printing.printlog.add({'job': j['name'], 'key': 'accounts', 'file': 'x', 'printer': 'OFFICE_MFP', + 'request_id': None, 'added': datetime.now(), 'error': 'lp: '}) + printing.printlog.add({'job': 'job-19990101-000000', 'key': 'ACC001', 'file': 'x', 'printer': 'OTHER', + 'request_id': 'OTHER-1', 'added': datetime.now(), 'error': None}) + body = self.get('/pdf?name=%s&key=ACC001' % j['name'])[1] + self.assertIn(b'Printed from this job', body) + self.assertIn(b'OFFICE_MFP-777', body) + self.assertIn(b'lp: <bad>', body) + self.assertNotIn(b'OTHER-1', body) + + def test_a_refused_print_says_why(self): + j = self.send_invoice() + with mock.patch.object(main, 'printFile', side_effect=printing.PrintError('lp: no such queue ')): + r, body = self.post('/print', name=j['name'], key='ACC001', printer='nope') + self.assertEqual(200, r.status) + self.assertIn(b'was not printed: lp: no such queue <x>', body) + def test_the_address_book_only_changes_on_a_post(self): self.send_invoice() # a GET with add or delete parameters (an old link, a bookmark, a refresh) changes nothing diff --git a/web/pdf.html b/web/pdf.html index 2df652c..3c6daf2 100644 --- a/web/pdf.html +++ b/web/pdf.html @@ -79,6 +79,22 @@

    Sent from this job

    % endif + % if printed_from_this_job: +

    Printed from this job

    + + + % for rec in printed_from_this_job: + + + + + + + + % endfor +
    SentDocumentPrinterCUPS request
    ${rec['added'].strftime('%d %b %Y %H:%M:%S') | h}${rec['key'] | h}${rec['printer'] | h}${rec['request_id'] or '' | h}${rec['error'] or '' | h}
    + % endif + From dee9d357efb4023acce8fda3cfdcd4480aab7140 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Fri, 20 Nov 2026 00:20:37 +0000 Subject: [PATCH 29/31] Printed Items page, listing what was sent to a printer like Sent Items does Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP --- main.py | 7 +++++++ test_integration.py | 16 +++++++++++++++- web/bootstrap.html | 1 + web/printed.html | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 web/printed.html diff --git a/main.py b/main.py index 62b5531..b441f86 100755 --- a/main.py +++ b/main.py @@ -305,6 +305,12 @@ def sent(query_string='', resp=None): rows.append(dict(p=p, job=ref[0] if ref else None, key=ref[1] if ref else None, loaded=bool(ref and ref[0] in loaded))) return ( template_lookup.get_template("/sent.html").render(rows=rows, total=len(results)), 'text/html') +def printed(query_string='', resp=None): + results = printing.printlog.records # newest first + loaded = set(j['name'] for j in jobs) + rows = [dict(p=p, loaded=p.get('job') in loaded) for p in results[:SENT_SHOWN]] + return ( template_lookup.get_template("/printed.html").render(rows=rows, total=len(results)), 'text/html') + def settings_email(query_string='', postreq=None, resp=None): """The address book. Adding and removing a contact change it, so they only happen on a POST, which then redirects back here: a refresh (or a bookmarked URL) shows the list and never repeats the change.""" @@ -614,6 +620,7 @@ def htmlcol(rgb): '/pdf':pdf, '/pdf_file': pdf_file, '/sent':sent, + '/printed':printed, '/print' : printfn, '/plaintext':plain, '/settings/email':settings_email, diff --git a/test_integration.py b/test_integration.py index d8e73c5..68c76f5 100644 --- a/test_integration.py +++ b/test_integration.py @@ -266,7 +266,7 @@ def test_http_endpoints(self): r, body = self.get('/pdf_file?name=%s&key=ACC001&attach=1' % name) self.assertIn('attachment', r.getheader('Content-Disposition')) - for path in ['/home', '/sent', '/printers', '/settings/email', '/settings/templates', + for path in ['/home', '/sent', '/printed', '/printers', '/settings/email', '/settings/templates', '/pdf?name=' + name, '/debug?name=' + name, '/plaintext?name=' + name, '/']: r, body = self.get(path) self.assertEqual(200, r.status, path) @@ -733,6 +733,20 @@ def test_print_history_is_listed_on_the_job_page(self): self.assertIn(b'lp: <bad>', body) self.assertNotIn(b'OTHER-1', body) + def test_printed_items_page(self): + j = self.send_invoice() + for job, req, err in [(j['name'], 'OFFICE_MFP-778', None), ('job-19990101-000000', None, 'lp: ')]: + printing.printlog.add({'job': job, 'key': 'ACC001', 'file': 'x', 'printer': 'OFFICE_MFP', + 'request_id': req, 'added': datetime.now(), 'error': err}) + r, body = self.get('/printed') + self.assertEqual(200, r.status) + self.assertIn(b'DocumentPrinterIDProblems?', body) + self.assertIn(('href="/pdf?name=%s&key=ACC001"' % j['name']).encode(), body) # loaded: linked + self.assertIn(b'OFFICE_MFP-778', body) + self.assertIn(b'lp: <bad>', body) + self.assertNotIn(b'name=job-19990101-000000', body) # no longer loaded: not linked + self.assertIn(b'Printed Items', body) + def test_a_refused_print_says_why(self): j = self.send_invoice() with mock.patch.object(main, 'printFile', side_effect=printing.PrintError('lp: no such queue ')): diff --git a/web/bootstrap.html b/web/bootstrap.html index daa3a41..046175f 100644 --- a/web/bootstrap.html +++ b/web/bootstrap.html @@ -38,6 +38,7 @@
  • Recent
  • Document
  • Sent Items
  • +
  • Printed Items
  • diff --git a/web/printed.html b/web/printed.html index b31ff7f..e966204 100644 --- a/web/printed.html +++ b/web/printed.html @@ -1,8 +1,8 @@ <%inherit file="bootstrap.html"/> -<%block name="title">- Printed Items +<%block name="title">- Printed Documents -

    Printed Items

    +

    Printed Documents

    % if total > len(rows):

    Showing the latest ${len(rows)} of ${total} printed documents.

    diff --git a/web/recent.html b/web/recent.html index 2854b21..c4824af 100644 --- a/web/recent.html +++ b/web/recent.html @@ -1,11 +1,11 @@ <%inherit file="bootstrap.html"/> -<%block name="title">- Recent +<%block name="title">- Recent Documents <%block name="query_block"> -

    Recent Jobs

    +

    Recent Documents

    % if len(jobs) == 0:

    No Jobs found!

    diff --git a/web/sent.html b/web/sent.html index 57c0b4e..8775f07 100644 --- a/web/sent.html +++ b/web/sent.html @@ -1,8 +1,8 @@ <%inherit file="bootstrap.html"/> -<%block name="title">- Sent Items +<%block name="title">- Sent Emails -

    Sent Items

    +

    Sent Emails

    % if total > len(rows):

    Showing the latest ${len(rows)} of ${total} sent emails.

    From 8bffabb5f3ba32ee5e9c9b23659f6a2755865be1 Mon Sep 17 00:00:00 2001 From: Chris Shucksmith Date: Fri, 20 Nov 2026 08:31:51 +0000 Subject: [PATCH 31/31] Parsing an lpstat date with a zone name no longer depends on the machine's timezone strptime's %Z only accepts UTC, GMT and the local zone's names, so the BST test passed on a London laptop and failed on the UTC CI runner. The zone name is dropped instead. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DKcyxWnp9B7ZMfow73wHmP --- printstatus.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/printstatus.py b/printstatus.py index a27994b..3c6d49c 100644 --- a/printstatus.py +++ b/printstatus.py @@ -52,7 +52,10 @@ def mask_uri(uri): def parse_date(text): """'Wed Sep 9 15:02:14 2026' (C locale) as a naive local datetime, else None.""" text = ' '.join(text.split()) - for fmt in ('%a %b %d %H:%M:%S %Y', '%a %d %b %Y %I:%M:%S %p %Z', '%a %d %b %Y %H:%M:%S %Z'): + # a trailing zone name ("BST") is dropped: strptime's %Z only knows UTC, GMT and the local zone's names, so + # it would parse on one machine and not another + text = re.sub(r' [A-Z]{2,5}$', '', text) + for fmt in ('%a %b %d %H:%M:%S %Y', '%a %d %b %Y %I:%M:%S %p', '%a %d %b %Y %H:%M:%S'): try: return datetime.strptime(text, fmt) except ValueError: