Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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