Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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