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.

220 lines
8.3KB

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