You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

258 line
9.8KB

  1. #!/usr/bin/python3
  2. # encoding: utf-8
  3. from __future__ import print_function
  4. import os, sys, argparse, datetime, subprocess
  5. import logging
  6. logging.basicConfig(level=logging.DEBUG)
  7. log = logging.getLogger()
  8. import invoice.db
  9. class SanityCheckError(Exception):
  10. pass
  11. class Application:
  12. my_company = "my-company"
  13. editor = os.environ.get("EDITOR") or "vim"
  14. viewer = os.environ.get("PAGER") or "less"
  15. tex_program = "pdflatex"
  16. pdf_program = "xdg-open"
  17. def __init__(self, template_path):
  18. self._parse_args()
  19. exec(open(os.path.expanduser(os.path.join(self.args.user_data, "config"))).read(),
  20. {"__builtins__": None}, self.__dict__)
  21. self.year = self.args.__dict__.pop("year")
  22. self.user_path = os.path.expanduser(self.args.__dict__.pop("user_data"))
  23. self.method = self.args.__dict__.pop("method")
  24. self.data_path = os.path.join(self.user_path, "{year}", "data", "{directory}")
  25. self.tmp_path = os.path.join(self.user_path, "tmp")
  26. self.output_path = os.path.join(self.user_path, "{year}", "output")
  27. self.template_path = template_path
  28. self.db = invoice.db.Database(
  29. year = self.year,
  30. data_path = self.data_path)
  31. def _parse_args(self):
  32. parser = argparse.ArgumentParser(
  33. description = "Pavel Šimerda's invoice CLI application.",
  34. conflict_handler = "resolve")
  35. parser.add_argument("--year", "-y", action="store")
  36. parser.add_argument("--user-data", "-d", action="store")
  37. parser.add_argument("--debug", "-D", action="store_const", dest="log_level", const=logging.DEBUG)
  38. #parser.add_argument("--verbose", "-v", action="store_const", dest="log_level", const=logging.INFO)
  39. #parser.add_argument("--config", "-C", action="store")
  40. parser.set_defaults(
  41. year = datetime.date.today().year,
  42. user_data = "~/.invoice",
  43. log_level = logging.INFO)
  44. subparsers = parser.add_subparsers(title="subcommands",
  45. description="valid subcommands",
  46. help="additional help")
  47. for list_ in "invoices", "companies":
  48. for action in "list", "summary", "new", "edit", "paid", "show", "pdf", "delete":
  49. if action in ("pdf", "paid", "summary") and list_ != "invoices":
  50. continue
  51. suffix = ''
  52. if list_ == "companies":
  53. suffix = "-companies" if action=="list" else "-company"
  54. method = getattr(self, "do_"+(action+suffix).replace("-", "_"))
  55. subparser = subparsers.add_parser(action+suffix, help=method.__doc__)
  56. if method == self.do_pdf:
  57. subparser.add_argument("--generate", "-g", action="store_true")
  58. if action == "delete":
  59. subparser.add_argument("--force", "-f", action="store_true")
  60. if action == "new":
  61. subparser.add_argument("name" if suffix else "company_name")
  62. if action in ("show", "pdf", "edit", "paid", "delete"):
  63. subparser.add_argument("selector", nargs="?")
  64. if action == "paid":
  65. subparser.add_argument("date")
  66. subparser.set_defaults(method=method)
  67. self.args = parser.parse_args()
  68. log.setLevel(self.args.__dict__.pop("log_level"))
  69. log.debug("Arguments: {0}".format(self.args))
  70. def run(self):
  71. try:
  72. self.method(**vars(self.args))
  73. except (SanityCheckError) as error:
  74. print("Error: {0} Use '--force' to suppress this check.".format(error), file=sys.stderr)
  75. if log.isEnabledFor(logging.DEBUG):
  76. raise
  77. except invoice.db.DatabaseError as error:
  78. print("Error: {0}".format(error), file=sys.stderr)
  79. if log.isEnabledFor(logging.DEBUG):
  80. raise
  81. def do_list(self):
  82. """List invoices."""
  83. for item in sorted(self.db.invoices):
  84. print(item)
  85. def do_summary(self):
  86. """Show invoice summary."""
  87. total = paid = 0
  88. for invoice in sorted(self.db.invoices):
  89. data = invoice.data()
  90. log.debug(data._data)
  91. print("{number:7} {date!s:10} {due!s:10} {paid!s:10} {sum:>6} {company_name}"
  92. .format(**data._data))
  93. total += data.sum
  94. if data.paid:
  95. paid += data.sum
  96. print()
  97. print("Total: {0:6}".format(total))
  98. print("Paid: {0:6}".format(paid))
  99. print("Unpaid: {0:6}".format(total-paid))
  100. def do_new(self, company_name):
  101. """Create and edit a new invoice."""
  102. item = self.db.invoices.new(company_name)
  103. self._edit(item._path)
  104. def do_edit(self, selector):
  105. """Edit invoice in external editor.
  106. The external editor is determined by EDITOR environment variable
  107. using 'vim' as the default. Item is edited in-place.
  108. """
  109. self._edit(self.db.invoices[selector]._path)
  110. def do_paid(self, selector, date):
  111. path = self.db.invoices[selector]._path
  112. with open(path, "a") as stream:
  113. stream.write("Paid: {0}\n".format(date))
  114. self._show(path)
  115. def _edit(self, path):
  116. log.debug("Editing file: {0}".format(path))
  117. assert os.path.exists(path)
  118. subprocess.call((self.editor, path))
  119. def do_show(self, selector):
  120. """View invoice in external viewer.
  121. The external viewer is determined by PAGER environment variable
  122. using 'less' as the default.
  123. """
  124. item = self.db.invoices[selector]
  125. self._show(item._path)
  126. def do_pdf(self, selector, generate):
  127. """Generate and view a PDF invoice.
  128. This requires Tempita 0.5.
  129. """
  130. import tempita
  131. invoice = self.db.invoices[selector]
  132. tmp_path = self.tmp_path.format(year=self.year)
  133. output_path = self.output_path.format(year=self.year)
  134. log.debug("tmp_path={0}".format(tmp_path))
  135. tex_template = os.path.join(self.template_path, "invoice.tex")
  136. tex_file = os.path.join(tmp_path, "{0}.tex".format(invoice._name))
  137. tmp_pdf_file = os.path.join(tmp_path, "{0}.pdf".format(invoice._name))
  138. pdf_file = os.path.join(output_path, "{0}.pdf".format(invoice._name))
  139. if generate:
  140. #if(not os.path.exists(pdf_file) or
  141. # os.path.getmtime(invoice._path) > os.path.getmtime(pdf_file)):
  142. issuer = self.db.companies[self.my_company]
  143. customer = self.db.companies[invoice.company_name]
  144. invoice_data = invoice.data()
  145. issuer_data = issuer.data()
  146. customer_data = customer.data()
  147. log.debug("Invoice: {0}".format(invoice_data._data))
  148. log.debug("Issuer: {0}".format(issuer_data._data))
  149. log.debug("Customer: {0}".format(customer_data._data))
  150. log.debug("Creating TeX invoice...")
  151. self._check_path(self.tmp_path)
  152. result = tempita.Template(open(tex_template).read()).substitute(
  153. invoice=invoice_data, issuer=issuer_data, customer=customer_data)
  154. open(tex_file, "w").write(str(result))
  155. assert(os.path.exists(tex_file))
  156. log.debug("Creating PDF invoice...")
  157. if subprocess.call((self.tex_program, "{0}.tex".format(invoice._name)), cwd=tmp_path) != 0:
  158. raise GenerationError("PDF generation failed.")
  159. assert(os.path.exists(tmp_pdf_file))
  160. log.debug("Moving PDF file to the output directory...")
  161. self._check_path(output_path)
  162. os.rename(tmp_pdf_file, pdf_file)
  163. assert(os.path.exists(pdf_file))
  164. log.debug("Running PDF viewer...")
  165. subprocess.call((self.pdf_program, pdf_file))
  166. def _check_path(self, path):
  167. if not os.path.exists(path):
  168. raise LookupError("Directory doesn't exist: {0}".format(path))
  169. def do_delete(self, selector, force):
  170. """List invoices."""
  171. if selector:
  172. invoice = self.db.invoices[selector]
  173. else:
  174. invoice = self.db.invoices.last()
  175. if not force:
  176. raise SanityCheckError("It is not recommended to delete invoices.")
  177. invoice.delete()
  178. def do_list_companies(self):
  179. """List companies."""
  180. for item in sorted(self.db.companies):
  181. print(item)
  182. def do_new_company(self, name):
  183. """Create and edit a new company."""
  184. item = self.db.companies.new(name)
  185. self._edit(item._path)
  186. def do_edit_company(self, selector):
  187. """Edit company in external editor.
  188. The external editor is determined by EDITOR environment variable
  189. using 'vim' as the default. Item is edited in-place.
  190. """
  191. item = self.db.companies[selector]
  192. self._edit(item._path)
  193. def do_show_company(self, selector):
  194. """View company in external viewer.
  195. The external viewer is determined by PAGER environment variable
  196. using 'less' as the default.
  197. """
  198. item = self.db.companies[selector]
  199. print("# {0}".format(item._name))
  200. self._show(item._path)
  201. def _show(self, path):
  202. log.debug("Viewing file: {0}".format(path))
  203. assert os.path.exists(path)
  204. print("# {0}".format(path))
  205. subprocess.call((self.viewer, path))
  206. def do_delete_company(self, selector, force):
  207. """Delete a company."""
  208. company = self.db.companies[selector]
  209. if not force:
  210. invoices = self.db.invoices.select({"company_name": company._name})
  211. if invoices:
  212. for invoice in invoices:
  213. log.info("Dependent invoice: {0}".format(invoice))
  214. raise SanityCheckError("This company is used by some invoices. You should not delete it.")
  215. company.delete()