Update copyright years again.
[org-mode.git] / contrib / lisp / org-invoice.el
blobc1340a73c8369d829277b3314d1e71ef69728066
1 ;;; org-invoice.el --- Help manage client invoices in OrgMode
2 ;;
3 ;; Copyright (C) 2008-2014 pmade inc. (Peter Jones pjones@pmade.com)
4 ;;
5 ;; This file is not part of GNU Emacs.
6 ;;
7 ;; Permission is hereby granted, free of charge, to any person obtaining
8 ;; a copy of this software and associated documentation files (the
9 ;; "Software"), to deal in the Software without restriction, including
10 ;; without limitation the rights to use, copy, modify, merge, publish,
11 ;; distribute, sublicense, and/or sell copies of the Software, and to
12 ;; permit persons to whom the Software is furnished to do so, subject to
13 ;; the following conditions:
15 ;; The above copyright notice and this permission notice shall be
16 ;; included in all copies or substantial portions of the Software.
18 ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 ;;; Commentary:
28 ;; Building on top of the terrific OrgMode, org-invoice tries to
29 ;; provide functionality for managing invoices. Currently, it does
30 ;; this by implementing an OrgMode dynamic block where invoice
31 ;; information is aggregated so that it can be exported.
33 ;; It also provides a library of functions that can be used to collect
34 ;; this invoice information and use it in other ways, such as
35 ;; submitting it to on-line invoicing tools.
37 ;; I'm already working on an elisp package to submit this invoice data
38 ;; to the FreshBooks on-line accounting tool.
40 ;; Usage:
42 ;; In your ~/.emacs:
43 ;; (autoload 'org-invoice-report "org-invoice")
44 ;; (autoload 'org-dblock-write:invoice "org-invoice")
46 ;; See the documentation in the following functions:
48 ;; `org-invoice-report'
49 ;; `org-dblock-write:invoice'
51 ;; Latest version:
53 ;; git clone git://pmade.com/elisp
54 (eval-when-compile
55 (require 'cl)
56 (require 'org))
58 (defgroup org-invoice nil
59 "OrgMode Invoice Helper"
60 :tag "Org-Invoice" :group 'org)
62 (defcustom org-invoice-long-date-format "%A, %B %d, %Y"
63 "The format string for long dates."
64 :type 'string :group 'org-invoice)
66 (defcustom org-invoice-strip-ts t
67 "Remove org timestamps that appear in headings."
68 :type 'boolean :group 'org-invoice)
70 (defcustom org-invoice-default-level 2
71 "The heading level at which a new invoice starts. This value
72 is used if you don't specify a scope option to the invoice block,
73 and when other invoice helpers are trying to find the heading
74 that starts an invoice.
76 The default is 2, assuming that you structure your invoices so
77 that they fall under a single heading like below:
79 * Invoices
80 ** This is invoice number 1...
81 ** This is invoice number 2...
83 If you don't structure your invoices using those conventions,
84 change this setting to the number that corresponds to the heading
85 at which an invoice begins."
86 :type 'integer :group 'org-invoice)
88 (defcustom org-invoice-start-hook nil
89 "Hook called when org-invoice is about to collect data from an
90 invoice heading. When this hook is called, point will be on the
91 heading where the invoice begins.
93 When called, `org-invoice-current-invoice' will be set to the
94 alist that represents the info for this invoice."
95 :type 'hook :group 'org-invoice)
97 (defcustom org-invoice-heading-hook nil
98 "Hook called when org-invoice is collecting data from a
99 heading. You can use this hook to add additional information to
100 the alist that represents the heading.
102 When this hook is called, point will be on the current heading
103 being processed, and `org-invoice-current-item' will contain the
104 alist for the current heading.
106 This hook is called repeatedly for each invoice item processed."
107 :type 'hook :group 'org-invoice)
109 (defvar org-invoice-current-invoice nil
110 "Information about the current invoice.")
112 (defvar org-invoice-current-item nil
113 "Information about the current invoice item.")
115 (defvar org-invoice-table-params nil
116 "The table parameters currently being used.")
118 (defvar org-invoice-total-time nil
119 "The total invoice time for the summary line.")
121 (defvar org-invoice-total-price nil
122 "The total invoice price for the summary line.")
124 (defconst org-invoice-version "1.0.0"
125 "The org-invoice version number.")
127 (defun org-invoice-goto-tree (&optional tree)
128 "Move point to the heading that represents the head of the
129 current invoice. The heading level will be taken from
130 `org-invoice-default-level' unless tree is set to a string that
131 looks like tree2, where the level is 2."
132 (let ((level org-invoice-default-level))
133 (save-match-data
134 (when (and tree (string-match "^tree\\([0-9]+\\)$" tree))
135 (setq level (string-to-number (match-string 1 tree)))))
136 (org-back-to-heading)
137 (while (and (> (org-reduced-level (org-outline-level)) level)
138 (org-up-heading-safe)))))
140 (defun org-invoice-heading-info ()
141 "Return invoice information from the current heading."
142 (let ((title (org-no-properties (org-get-heading t)))
143 (date (org-entry-get nil "TIMESTAMP" 'selective))
144 (work (org-entry-get nil "WORK" nil))
145 (rate (or (org-entry-get nil "RATE" t) "0"))
146 (level (org-outline-level))
147 raw-date long-date)
148 (unless date (setq date (org-entry-get nil "TIMESTAMP_IA" 'selective)))
149 (unless date (setq date (org-entry-get nil "TIMESTAMP" t)))
150 (unless date (setq date (org-entry-get nil "TIMESTAMP_IA" t)))
151 (unless work (setq work (org-entry-get nil "CLOCKSUM" nil)))
152 (unless work (setq work "00:00"))
153 (when date
154 (setq raw-date (apply 'encode-time (org-parse-time-string date)))
155 (setq long-date (format-time-string org-invoice-long-date-format raw-date)))
156 (when (and org-invoice-strip-ts (string-match org-ts-regexp-both title))
157 (setq title (replace-match "" nil nil title)))
158 (when (string-match "^[ \t]+" title)
159 (setq title (replace-match "" nil nil title)))
160 (when (string-match "[ \t]+$" title)
161 (setq title (replace-match "" nil nil title)))
162 (setq work (org-hh:mm-string-to-minutes work))
163 (setq rate (string-to-number rate))
164 (setq org-invoice-current-item (list (cons 'title title)
165 (cons 'date date)
166 (cons 'raw-date raw-date)
167 (cons 'long-date long-date)
168 (cons 'work work)
169 (cons 'rate rate)
170 (cons 'level level)
171 (cons 'price (* rate (/ work 60.0)))))
172 (run-hook-with-args 'org-invoice-heading-hook)
173 org-invoice-current-item))
175 (defun org-invoice-level-min-max (ls)
176 "Return a list where the car is the min level, and the cdr the max."
177 (let ((max 0) min level)
178 (dolist (info ls)
179 (when (cdr (assoc 'date info))
180 (setq level (cdr (assoc 'level info)))
181 (when (or (not min) (< level min)) (setq min level))
182 (when (> level max) (setq max level))))
183 (cons (or min 0) max)))
185 (defun org-invoice-collapse-list (ls)
186 "Reorganize the given list by dates."
187 (let ((min-max (org-invoice-level-min-max ls)) new)
188 (dolist (info ls)
189 (let* ((date (cdr (assoc 'date info)))
190 (work (cdr (assoc 'work info)))
191 (price (cdr (assoc 'price info)))
192 (long-date (cdr (assoc 'long-date info)))
193 (level (cdr (assoc 'level info)))
194 (bucket (cdr (assoc date new))))
195 (if (and (/= (car min-max) (cdr min-max))
196 (= (car min-max) level)
197 (= work 0) (not bucket) date)
198 (progn
199 (setq info (assq-delete-all 'work info))
200 (push (cons 'total-work 0) info)
201 (push (cons date (list info)) new)
202 (setq bucket (cdr (assoc date new))))
203 (when (and date (not bucket))
204 (setq bucket (list (list (cons 'date date)
205 (cons 'title long-date)
206 (cons 'total-work 0)
207 (cons 'price 0))))
208 (push (cons date bucket) new)
209 (setq bucket (cdr (assoc date new))))
210 (when (and date bucket)
211 (setcdr (assoc 'total-work (car bucket))
212 (+ work (cdr (assoc 'total-work (car bucket)))))
213 (setcdr (assoc 'price (car bucket))
214 (+ price (cdr (assoc 'price (car bucket)))))
215 (nconc bucket (list info))))))
216 (nreverse new)))
218 (defun org-invoice-info-to-table (info)
219 "Create a single org table row from the given info alist."
220 (let ((title (cdr (assoc 'title info)))
221 (total (cdr (assoc 'total-work info)))
222 (work (cdr (assoc 'work info)))
223 (price (cdr (assoc 'price info)))
224 (with-price (plist-get org-invoice-table-params :price)))
225 (unless total
226 (setq
227 org-invoice-total-time (+ org-invoice-total-time work)
228 org-invoice-total-price (+ org-invoice-total-price price)))
229 (setq total (and total (org-minutes-to-clocksum-string total)))
230 (setq work (and work (org-minutes-to-clocksum-string work)))
231 (insert-before-markers
232 (concat "|" title
233 (cond
234 (total (concat "|" total))
235 (work (concat "|" work)))
236 (and with-price price (concat "|" (format "%.2f" price)))
237 "|" "\n"))))
239 (defun org-invoice-list-to-table (ls)
240 "Convert a list of heading info to an org table"
241 (let ((with-price (plist-get org-invoice-table-params :price))
242 (with-summary (plist-get org-invoice-table-params :summary))
243 (with-header (plist-get org-invoice-table-params :headers))
244 (org-invoice-total-time 0)
245 (org-invoice-total-price 0))
246 (insert-before-markers
247 (concat "| Task / Date | Time" (and with-price "| Price") "|\n"))
248 (dolist (info ls)
249 (insert-before-markers "|-\n")
250 (mapc 'org-invoice-info-to-table (if with-header (cdr info) (cdr (cdr info)))))
251 (when with-summary
252 (insert-before-markers
253 (concat "|-\n|Total:|"
254 (org-minutes-to-clocksum-string org-invoice-total-time)
255 (and with-price (concat "|" (format "%.2f" org-invoice-total-price)))
256 "|\n")))))
258 (defun org-invoice-collect-invoice-data ()
259 "Collect all the invoice data from the current OrgMode tree and
260 return it. Before you call this function, move point to the
261 heading that begins the invoice data, usually using the
262 `org-invoice-goto-tree' function."
263 (let ((org-invoice-current-invoice
264 (list (cons 'point (point)) (cons 'buffer (current-buffer))))
265 (org-invoice-current-item nil))
266 (save-restriction
267 (org-narrow-to-subtree)
268 (org-clock-sum)
269 (run-hook-with-args 'org-invoice-start-hook)
270 (cons org-invoice-current-invoice
271 (org-invoice-collapse-list
272 (org-map-entries 'org-invoice-heading-info t 'tree 'archive))))))
274 (defun org-dblock-write:invoice (params)
275 "Function called by OrgMode to write the invoice dblock. To
276 create an invoice dblock you can use the `org-invoice-report'
277 function.
279 The following parameters can be given to the invoice block (for
280 information about dblock parameters, please see the Org manual):
282 :scope Allows you to override the `org-invoice-default-level'
283 variable. The only supported values right now are ones
284 that look like :tree1, :tree2, etc.
286 :prices Set to nil to turn off the price column.
288 :headers Set to nil to turn off the group headers.
290 :summary Set to nil to turn off the final summary line."
291 (let ((scope (plist-get params :scope))
292 (org-invoice-table-params params)
293 (zone (point-marker))
294 table)
295 (unless scope (setq scope 'default))
296 (unless (plist-member params :price) (plist-put params :price t))
297 (unless (plist-member params :summary) (plist-put params :summary t))
298 (unless (plist-member params :headers) (plist-put params :headers t))
299 (save-excursion
300 (cond
301 ((eq scope 'tree) (org-invoice-goto-tree "tree1"))
302 ((eq scope 'default) (org-invoice-goto-tree))
303 ((symbolp scope) (org-invoice-goto-tree (symbol-name scope))))
304 (setq table (org-invoice-collect-invoice-data))
305 (goto-char zone)
306 (org-invoice-list-to-table (cdr table))
307 (goto-char zone)
308 (org-table-align)
309 (move-marker zone nil))))
311 (defun org-invoice-in-report-p ()
312 "Check to see if point is inside an invoice report."
313 (let ((pos (point)) start)
314 (save-excursion
315 (end-of-line 1)
316 (and (re-search-backward "^#\\+BEGIN:[ \t]+invoice" nil t)
317 (setq start (match-beginning 0))
318 (re-search-forward "^#\\+END:.*" nil t)
319 (>= (match-end 0) pos)
320 start))))
322 (defun org-invoice-report (&optional jump)
323 "Create or update an invoice dblock report. If point is inside
324 an existing invoice report, the report is updated. If point
325 isn't inside an invoice report, a new report is created.
327 When called with a prefix argument, move to the first invoice
328 report after point and update it.
330 For information about various settings for the invoice report,
331 see the `org-dblock-write:invoice' function documentation.
333 An invoice report is created by reading a heading tree and
334 collecting information from various properties. It is assumed
335 that all invoices start at a second level heading, but this can
336 be configured using the `org-invoice-default-level' variable.
338 Here is an example, where all invoices fall under the first-level
339 heading Invoices:
341 * Invoices
342 ** Client Foo (Jan 01 - Jan 15)
343 *** [2008-01-01 Tue] Built New Server for Production
344 *** [2008-01-02 Wed] Meeting with Team to Design New System
345 ** Client Bar (Jan 01 - Jan 15)
346 *** [2008-01-01 Tue] Searched for Widgets on Google
347 *** [2008-01-02 Wed] Billed You for Taking a Nap
349 In this layout, invoices begin at level two, and invoice
350 items (tasks) are at level three. You'll notice that each level
351 three heading starts with an inactive timestamp. The timestamp
352 can actually go anywhere you want, either in the heading, or in
353 the text under the heading. But you must have a timestamp
354 somewhere so that the invoice report can group your items by
355 date.
357 Properties are used to collect various bits of information for
358 the invoice. All properties can be set on the invoice item
359 headings, or anywhere in the tree. The invoice report will scan
360 up the tree looking for each of the properties.
362 Properties used:
364 CLOCKSUM: You can use the Org clock-in and clock-out commands to
365 create a CLOCKSUM property. Also see WORK.
367 WORK: An alternative to the CLOCKSUM property. This property
368 should contain the amount of work that went into this
369 invoice item formatted as HH:MM (e.g. 01:30).
371 RATE: Used to calculate the total price for an invoice item.
372 Should be the price per hour that you charge (e.g. 45.00).
373 It might make more sense to place this property higher in
374 the hierarchy than on the invoice item headings.
376 Using this information, a report is generated that details the
377 items grouped by days. For each day you will be able to see the
378 total number of hours worked, the total price, and the items
379 worked on.
381 You can place the invoice report anywhere in the tree you want.
382 I place mine under a third-level heading like so:
384 * Invoices
385 ** An Invoice Header
386 *** [2008-11-25 Tue] An Invoice Item
387 *** Invoice Report
388 #+BEGIN: invoice
389 #+END:"
390 (interactive "P")
391 (let ((report (org-invoice-in-report-p)))
392 (when (and (not report) jump)
393 (when (re-search-forward "^#\\+BEGIN:[ \t]+invoice" nil t)
394 (org-show-entry)
395 (beginning-of-line)
396 (setq report (point))))
397 (if report (goto-char report)
398 (org-create-dblock (list :name "invoice")))
399 (org-update-dblock)))
401 (provide 'org-invoice)