Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

235 lines
8.9KB

  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", "pdf", "delete":
  44. if action == "pdf" and list_ != "invoices":
  45. continue
  46. suffix = ''
  47. if list_ == "companies":
  48. suffix = "-companies" if action=="list" else "-company"
  49. method = getattr(self, "do_"+(action+suffix).replace("-", "_"))
  50. subparser = subparsers.add_parser(action+suffix, help=method.__doc__)
  51. if method == self.do_pdf:
  52. subparser.add_argument("--generate", "-g", action="store_true")
  53. if action == "delete":
  54. subparser.add_argument("--force", "-f", action="store_true")
  55. if action == "new":
  56. subparser.add_argument("name" if suffix else "company_name")
  57. if action in ("show", "pdf", "edit", "delete"):
  58. subparser.add_argument("selector", nargs="?")
  59. subparser.set_defaults(method=method)
  60. self.args = parser.parse_args()
  61. log.setLevel(self.args.__dict__.pop("log_level"))
  62. log.debug("Arguments: {}".format(self.args))
  63. def run(self):
  64. try:
  65. self.method(**vars(self.args))
  66. except (SanityCheckError) as error:
  67. print("Error: {} Use '--force' to suppress this check.".format(error), file=sys.stderr)
  68. if log.isEnabledFor(logging.DEBUG):
  69. raise
  70. except invoice.db.DatabaseError as error:
  71. print("Error: {}".format(error), file=sys.stderr)
  72. if log.isEnabledFor(logging.DEBUG):
  73. raise
  74. def do_list(self):
  75. """List invoices."""
  76. for item in sorted(self.db.invoices):
  77. print(item)
  78. def do_new(self, company_name):
  79. """Create and edit a new invoice."""
  80. item = self.db.invoices.new(company_name)
  81. self._edit(item._path)
  82. def do_edit(self, selector):
  83. """Edit invoice in external editor.
  84. The external editor is determined by EDITOR environment variable
  85. using 'vim' as the default. Item is edited in-place.
  86. """
  87. if selector:
  88. item = self.db.invoices[selector]
  89. else:
  90. item = self.db.invoices.last()
  91. self._edit(item._path)
  92. def _edit(self, path):
  93. log.debug("Editing file: {}".format(path))
  94. assert os.path.exists(path)
  95. subprocess.call((self.editor, path))
  96. def do_show(self, selector):
  97. """View invoice in external viewer.
  98. The external viewer is determined by PAGER environment variable
  99. using 'less' as the default.
  100. """
  101. item = self.db.invoices[selector]
  102. self._show(item._path)
  103. def do_pdf(self, selector, generate):
  104. """Generate and view a PDF invoice.
  105. This requires Tempita 0.5.
  106. """
  107. import tempita
  108. if selector:
  109. invoice = self.db.invoices[selector]
  110. else:
  111. invoice = self.db.invoices.last()
  112. tmp_path = self.tmp_path.format(year=self.year)
  113. output_path = self.output_path.format(year=self.year)
  114. log.debug("tmp_path={}".format(tmp_path))
  115. tex_template = os.path.join(self.template_path, "invoice.tex")
  116. tex_file = os.path.join(tmp_path, "{}.tex".format(invoice._name))
  117. tmp_pdf_file = os.path.join(tmp_path, "{}.pdf".format(invoice._name))
  118. pdf_file = os.path.join(output_path, "{}.pdf".format(invoice._name))
  119. if generate:
  120. if(not os.path.exists(pdf_file) or
  121. os.path.getmtime(invoice._path) > os.path.getmtime(pdf_file)):
  122. issuer = self.db.companies[self.my_company]
  123. customer = self.db.companies[invoice.company_name]
  124. invoice_data = invoice.data()
  125. issuer_data = issuer.data()
  126. customer_data = customer.data()
  127. log.debug("Invoice: {}".format(invoice_data._data))
  128. log.debug("Issuer: {}".format(issuer_data._data))
  129. log.debug("Customer: {}".format(customer_data._data))
  130. log.debug("Creating TeX invoice...")
  131. self._check_path(self.tmp_path)
  132. result = tempita.Template(open(tex_template).read()).substitute(
  133. invoice=invoice_data, issuer=issuer_data, customer=customer_data)
  134. open(tex_file, "w").write(str(result))
  135. assert(os.path.exists(tex_file))
  136. log.debug("Creating PDF invoice...")
  137. if subprocess.call((self.tex_program, "{}.tex".format(invoice._name)), cwd=tmp_path) != 0:
  138. raise GenerationError("PDF generation failed.")
  139. assert(os.path.exists(tmp_pdf_file))
  140. log.debug("Moving PDF file to the output directory...")
  141. self._check_path(output_path)
  142. os.rename(tmp_pdf_file, pdf_file)
  143. else:
  144. log.info("PDF file is up to date.")
  145. assert(os.path.exists(pdf_file))
  146. log.debug("Running PDF viewer...")
  147. subprocess.call((self.pdf_program, pdf_file))
  148. def _check_path(self, path):
  149. if not os.path.exists(path):
  150. raise LookupError("Directory doesn't exist: {}".format(path))
  151. def do_delete(self, selector, force):
  152. """List invoices."""
  153. if selector:
  154. invoice = self.db.invoices[selector]
  155. else:
  156. invoice = self.db.invoices.last()
  157. if not force:
  158. raise SanityCheckError("It is not recommended to delete invoices.")
  159. invoice.delete()
  160. def do_list_companies(self):
  161. """List companies."""
  162. for item in sorted(self.db.companies):
  163. print(item)
  164. def do_new_company(self, name):
  165. """Create and edit a new company."""
  166. item = self.db.companies.new(name)
  167. self._edit(item._path)
  168. def do_edit_company(self, selector):
  169. """Edit company in external editor.
  170. The external editor is determined by EDITOR environment variable
  171. using 'vim' as the default. Item is edited in-place.
  172. """
  173. item = self.db.companies[selector]
  174. self._edit(item._path)
  175. def do_show_company(self, selector):
  176. """View company in external viewer.
  177. The external viewer is determined by PAGER environment variable
  178. using 'less' as the default.
  179. """
  180. item = self.db.companies[selector]
  181. self._show(item._path)
  182. def _show(self, path):
  183. log.debug("Viewing file: {}".format(path))
  184. assert os.path.exists(path)
  185. subprocess.call((self.viewer, path))
  186. def do_delete_company(self, selector, force):
  187. """Delete a company."""
  188. company = self.db.companies[selector]
  189. if not force:
  190. invoices = self.db.invoices.select({"company_name": company._name})
  191. if invoices:
  192. for invoice in invoices:
  193. log.info("Dependent invoice: {}".format(invoice))
  194. raise SanityCheckError("This company is used by some invoices. You should not delete it.")
  195. company.delete()