Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. self._edit(self.db.invoices[selector]._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. """View invoice in external viewer.
  94. The external viewer is determined by PAGER environment variable
  95. using 'less' as the default.
  96. """
  97. item = self.db.invoices[selector]
  98. self._show(item._path)
  99. def do_pdf(self, selector, generate):
  100. """Generate and view a PDF invoice.
  101. This requires Tempita 0.5.
  102. """
  103. import tempita
  104. invoice = self.db.invoices[selector]
  105. tmp_path = self.tmp_path.format(year=self.year)
  106. output_path = self.output_path.format(year=self.year)
  107. log.debug("tmp_path={}".format(tmp_path))
  108. tex_template = os.path.join(self.template_path, "invoice.tex")
  109. tex_file = os.path.join(tmp_path, "{}.tex".format(invoice._name))
  110. tmp_pdf_file = os.path.join(tmp_path, "{}.pdf".format(invoice._name))
  111. pdf_file = os.path.join(output_path, "{}.pdf".format(invoice._name))
  112. if generate:
  113. if(not os.path.exists(pdf_file) or
  114. os.path.getmtime(invoice._path) > os.path.getmtime(pdf_file)):
  115. issuer = self.db.companies[self.my_company]
  116. customer = self.db.companies[invoice.company_name]
  117. invoice_data = invoice.data()
  118. issuer_data = issuer.data()
  119. customer_data = customer.data()
  120. log.debug("Invoice: {}".format(invoice_data._data))
  121. log.debug("Issuer: {}".format(issuer_data._data))
  122. log.debug("Customer: {}".format(customer_data._data))
  123. log.debug("Creating TeX invoice...")
  124. self._check_path(self.tmp_path)
  125. result = tempita.Template(open(tex_template).read()).substitute(
  126. invoice=invoice_data, issuer=issuer_data, customer=customer_data)
  127. open(tex_file, "w").write(str(result))
  128. assert(os.path.exists(tex_file))
  129. log.debug("Creating PDF invoice...")
  130. if subprocess.call((self.tex_program, "{}.tex".format(invoice._name)), cwd=tmp_path) != 0:
  131. raise GenerationError("PDF generation failed.")
  132. assert(os.path.exists(tmp_pdf_file))
  133. log.debug("Moving PDF file to the output directory...")
  134. self._check_path(output_path)
  135. os.rename(tmp_pdf_file, pdf_file)
  136. else:
  137. log.info("PDF file is up to date.")
  138. assert(os.path.exists(pdf_file))
  139. log.debug("Running PDF viewer...")
  140. subprocess.call((self.pdf_program, pdf_file))
  141. def _check_path(self, path):
  142. if not os.path.exists(path):
  143. raise LookupError("Directory doesn't exist: {}".format(path))
  144. def do_delete(self, selector, force):
  145. """List invoices."""
  146. if selector:
  147. invoice = self.db.invoices[selector]
  148. else:
  149. invoice = self.db.invoices.last()
  150. if not force:
  151. raise SanityCheckError("It is not recommended to delete invoices.")
  152. invoice.delete()
  153. def do_list_companies(self):
  154. """List companies."""
  155. for item in sorted(self.db.companies):
  156. print(item)
  157. def do_new_company(self, name):
  158. """Create and edit a new company."""
  159. item = self.db.companies.new(name)
  160. self._edit(item._path)
  161. def do_edit_company(self, selector):
  162. """Edit company in external editor.
  163. The external editor is determined by EDITOR environment variable
  164. using 'vim' as the default. Item is edited in-place.
  165. """
  166. item = self.db.companies[selector]
  167. self._edit(item._path)
  168. def do_show_company(self, selector):
  169. """View company in external viewer.
  170. The external viewer is determined by PAGER environment variable
  171. using 'less' as the default.
  172. """
  173. item = self.db.companies[selector]
  174. self._show(item._path)
  175. def _show(self, path):
  176. log.debug("Viewing file: {}".format(path))
  177. assert os.path.exists(path)
  178. subprocess.call((self.viewer, path))
  179. def do_delete_company(self, selector, force):
  180. """Delete a company."""
  181. company = self.db.companies[selector]
  182. if not force:
  183. invoices = self.db.invoices.select({"company_name": company._name})
  184. if invoices:
  185. for invoice in invoices:
  186. log.info("Dependent invoice: {}".format(invoice))
  187. raise SanityCheckError("This company is used by some invoices. You should not delete it.")
  188. company.delete()