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ů.

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