Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

285 linhas
11KB

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