You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cli.py 10KB

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