
;; $Author: chris $ $Date: 2009/07/29 09:31:44 $ $Revision: 1.33 $
;; Modified by Dmitry Smirnov <onlyjob@member.fsf.org>  14 Feb 2012
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2 of the
;; License, or (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;; General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
;; 02111-1307 USA

; put the (define-module... back when installing as a 'proper' report
; as opposed to referring to it from .gnucash/config.user
; (see http://wiki.gnucash.org/wiki/Custom_Reports )
(define-module (gnucash report taxinvoice))        

(use-modules (gnucash main))
(use-modules (gnucash gnc-module))        
(use-modules (gnucash app-utils))
(use-modules (gnucash business-utils))
(gnc:module-load "gnucash/report/report-system" 0)
(gnc:module-load "gnucash/business-utils" 0)
(gnc:module-load "gnucash/html" 0)
(gnc:module-load "gnucash/engine" 0)

(use-modules (gnucash report standard-reports))
(use-modules (gnucash report business-reports))

(use-modules (gnucash report eguile-utilities))
(use-modules (gnucash report eguile-html-utilities))
(use-modules (gnucash report eguile-gnc))

(use-modules (srfi srfi-13)) ; for extra string functions

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Report-specific routines

(define (taxrate taxable taxtable curr)
  ;; Display the tax rate applicable to an invoice line.
  ;; This may be e.g. "15%" or "£5.00" or "15% + £5.00" or "n/a"
  ;; depending on how complicated the tax table is.
  ;; (When called from within the eguile template, anything
  ;; (display)ed becomes part of the HTML string.)
  (if (or (not taxable) (eq? taxtable '()))
    (display "&nbsp;")
    (let* ((amttot  (gnc:make-commodity-collector))
           (pctot   (gnc:make-numeric-collector)) 
           (entries (gncTaxTableGetEntries taxtable))
           (amt?    #f)  ; becomes #t if any entries are amounts
           (pc?     #f)) ; becomes #t if any entries are percentages
      (for entry in entries do
          (let ((tttype (gncTaxTableEntryGetType   entry))
                (ttamt  (gncTaxTableEntryGetAmount entry)))
            (if (equal? tttype GNC-AMT-TYPE-VALUE)
              (begin
                (set! amt? #t)
                (amttot 'add curr ttamt))
              (begin
                (set! pc? #t)
                (pctot 'add ttamt)))))
      (if pc? (begin (display (fmtnumeric (pctot 'total #f))) (display "%")))
      (if (and amt? pc?) (display " +&nbsp;"))        ; both - this seems unlikely in practice
      (if amt?
        (display-comm-coll-total amttot #f))
      (if (and (not amt?) (not pc?)) (display (_ "n/a"))))))        ; neither

(define (coy-info slots key)
  ;; Extract a value from the company info key-value pairs
  (kvp-frame-get-slot-path-gslist
    slots 
    (append gnc:*kvp-option-path* (list gnc:*business-label* key))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Define all the options

; option pages
(define headingpage  (N_ "Headings 1"))
(define headingpage2 (N_ "Headings 2"))
(define notespage    (N_ "Notes"))
;(define filespage    (N_ "Files"))
(define displaypage  (N_ "Display"))
(define generalpage  gnc:pagename-general)
(define elementspage			(N_ "Elements"))
; option names 
(define optname-col-date		(N_ "column: Date"))
(define optname-col-taxrate		(N_ "column: Tax Rate"))
(define optname-col-taxamount		(N_ "column: Tax Amount"))
(define optname-col-units		(N_ "column: Units"))
(define optname-col-netprice		(N_ "column: Net Price"))
(define optname-col-totalprice		(N_ "column: Total Price"))
(define optname-row-taxrate		(N_ "row: Tax Rate"))
(define optname-row-taxamount		(N_ "row: Total Tax Amount"))
(define optname-row-netprice		(N_ "row: Total Net Price"))
(define optname-row-totalprice		(N_ "row: Total Price"))
(define optname-row-address		(N_ "row: Bank Deposit Info"))
(define optname-row-contact-top		(N_ "row: Contact at the top"))
(define optname-row-contact-bottom	(N_ "row: Contact at the bottom"))
(define optname-row-invoice-number	(N_ "row: Invoice Number"))
(define optname-row-company-name	(N_ "row: Company Name"))
(define optname-row-subtotals     	(N_ "row: Generic subtotals"))
(define optname-report-currency		(N_ "Report Currency"))
(define optname-invoice-number-text	(N_ "Invoice number text"))
(define optname-to-text			(N_ "To text"))
(define optname-ref-text		(N_ "Ref text"))
(define optname-jobname-text		(N_ "Job Number text"))
(define optname-jobnumber-text		(N_ "Job Name text"))
(define optname-jobname-show		(N_ "Show Job name"))
(define optname-jobnumber-show		(N_ "Show Job number"))
(define optname-invnum-next-to-title	(N_ "Invoice number next to title"))
(define optname-border-collapse		(N_ "table-border-collapse"))
(define optname-border-color-th		(N_ "table-header-border-color"))
(define optname-border-color-td		(N_ "table-cell-border-color"))
(define optname-extra-css		(N_ "Embedded CSS"))
(define optname-report-title   (N_ "Report title"))
(define optname-invoice-number (N_ "Invoice number"))
(define optname-template-file  (N_ "Template file"))
(define optname-css-file       (N_ "CSS stylesheet file"))
(define optname-heading-font   (N_ "Heading font"))
(define optname-text-font      (N_ "Text font"))
(define optname-logofile       (N_ "Logo filename"))
(define optname-logo-width     (N_ "Logo width"))
(define optname-units          (N_ "Units"))
(define optname-qty            (N_ "Qty"))
(define optname-unit-price     (N_ "Unit Price"))
(define optname-disc-rate      (N_ "Discount Rate"))
(define optname-disc-amount    (N_ "Discount Amount"))
(define optname-net-price      (N_ "Net Price"))
(define optname-tax-rate       (N_ "Tax Rate"))
(define optname-tax-amount     (N_ "Tax Amount"))
(define optname-total-price    (N_ "Total Price"))
(define optname-subtotal       (N_ "Sub-total"))
(define optname-amount-due     (N_ "Amount Due"))
(define optname-payment-recd   (N_ "Payment received text"))
(define optname-extra-notes    (N_ "Extra notes"))

; Choose only customer invoices
; (This doesn't work very nicely -- all invoices and bills
;  are offered for selection, but if a non-customer invoice
;  is selected, the user is dumped back to viewing the
;  previous invoice (or none) with no error message)
(define (customers-only invoice)
  (let* ((owner     (gncInvoiceGetOwner  invoice))
         (endowner  (gncOwnerGetEndOwner owner))
         (ownertype (gncOwnerGetType     endowner)))
    ;(gnc:debug "ownertype is ")(gnc:debug ownertype)
    (if (eqv? ownertype GNC-OWNER-CUSTOMER)
      (list #t invoice)
      (list #f invoice))))

(define (options-generator)
  ;; Options
  (define report-options (gnc:new-options))
  (define (add-option new-option)
    (gnc:register-option report-options new-option))

  (add-option
    (gnc:make-invoice-option ; defined in gnucash/scm/business-options.scm
      generalpage optname-invoice-number 
      "a" "" (lambda () '()) 
      #f))        ;customers-only)) ;-- see above

(add-option (gnc:make-currency-option		gnc:pagename-general	optname-report-currency		"b" "" (N_ "")))

  ;; Elements page options
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-date		"a" (N_ "Display the date?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-units		"b" (N_ "Display the Units?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-netprice		"c" (N_ "Display the Net Price as a column?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-taxrate		"d" (N_ "Display the Tax Rate as a column?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-taxamount		"e" (N_ "Display the Tax Amount as a column?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-col-totalprice		"f" (N_ "Display the Total Price as a column?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-netprice		"g" (N_ "Display the Net Price as a subtotal row?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-taxrate		"h" (N_ "Display the Tax Rate as a subtotal row?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-taxamount		"i" (N_ "Display the Tax Amount as a subtotal row?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-totalprice		"j" (N_ "Display the Total Price as a subtotal row?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-subtotals		"k" (N_ "Display the generic subtotals row?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-contact-top		"l" (N_ "Display the contact at the top?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-contact-bottom	"m" (N_ "Display the contact at the bottom?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-address		"n" (N_ "Display bank deposit info? (use company address field)") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-invoice-number	"o" (N_ "Display the Invoice Number?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-row-company-name	"p" (N_ "Display the Company Name?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-invnum-next-to-title	"q" (N_ "Invoice Number next to title?") #f))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-jobname-show		"r" (N_ "Display Job name?") #t))
(add-option (gnc:make-simple-boolean-option	elementspage	optname-jobnumber-show		"s" (N_ "Invoice Job number?") #f))

  ;; Display options
  (add-option (gnc:make-string-option displaypage optname-template-file "a" 
    (N_ "The file name of the eguile template part of this report.  This file should either be in your .gnucash directory, or else in its proper place within the GnuCash installation directories.")
    "taxinvoice.eguile.scm"))
  (add-option (gnc:make-string-option displaypage optname-css-file "b" 
    (N_ "The file name of the CSS stylesheet to use with this report.  This file should either be in your .gnucash directory, or else in its proper place within the GnuCash installation directories.") 
    "taxinvoice.css"))
  (add-option (gnc:make-font-option 
                displaypage optname-heading-font "c" 
                (N_ "Font to use for the main heading") "Bank Gothic Medium 22"))
  (add-option (gnc:make-font-option 
                displaypage optname-text-font "d" 
                (N_ "Font to use for everything else") "Courier New 8"))
  (add-option (gnc:make-pixmap-option
                displaypage optname-logofile "e" 
                (N_ "Name of a file containing a logo to be used on the report") 
                ""))
  (add-option (gnc:make-string-option
                displaypage optname-logo-width "f" (N_ "Width of the logo in CSS format, e.g. 10% or 32px.  Leave blank to display the logo at its natural width.  The height of the logo will be scaled accordingly.") ""))
(add-option (gnc:make-simple-boolean-option	displaypage	optname-border-collapse	"g" (N_ "Border-collapse?") #t))
(add-option (gnc:make-string-option		displaypage	optname-border-color-th "h" "CSS color" (N_ "black")))
(add-option (gnc:make-string-option		displaypage	optname-border-color-td "i" "CSS color" (N_ "black")))

  ;; Heading options
  (add-option (gnc:make-string-option
                ; page / name / orderkey / tooltip / default
                headingpage optname-report-title "a" "" (_ "Tax Invoice")))
  (add-option (gnc:make-string-option
                headingpage optname-units "b" "" (_ "Units")))
  (add-option (gnc:make-string-option
                headingpage optname-qty "c" "" (_ "Qty")))
  (add-option (gnc:make-string-option
                headingpage optname-unit-price "d" "" (_ "Unit")))
  (add-option (gnc:make-string-option
                headingpage optname-disc-rate "e" "" (_ "Discount Rate")))
  (add-option (gnc:make-string-option
                headingpage optname-disc-amount "f" "" (_ "Discount Amount")))
  (add-option (gnc:make-string-option
                headingpage optname-net-price "g" "" (_ "Net Price")))
  (add-option (gnc:make-string-option
                headingpage optname-tax-rate "h" "" (_ "GST Rate")))
  (add-option (gnc:make-string-option
                headingpage optname-tax-amount "i" "" (_ "GST Amount")))
  (add-option (gnc:make-string-option
                headingpage optname-total-price "j" "" (_ "Total Price")))
  (add-option (gnc:make-string-option
                headingpage2 optname-subtotal "a" "" (_ "Sub-total")))
  (add-option (gnc:make-string-option
                headingpage2 optname-amount-due "b" "" (_ "Amount Due (inc GST)")))
  (add-option (gnc:make-string-option
                headingpage2 optname-payment-recd "c" "" 
                (_ "Payment received, thank you.")))
  (add-option (gnc:make-string-option	headingpage2	optname-invoice-number-text
    "d" "" (N_ "Invoice #:")))
  (add-option (gnc:make-string-option	headingpage2	optname-to-text
    "e" "" (N_ "To:")))
  (add-option (gnc:make-string-option	headingpage2	optname-ref-text
    "f" "" (N_ "Reference:")))
  (add-option (gnc:make-string-option	headingpage2	optname-jobnumber-text
    "g" "" (N_ "Job number:")))
  (add-option (gnc:make-string-option	headingpage2	optname-jobname-text
    "h" "" (N_ "Engagement:")))

  (add-option (gnc:make-text-option
                notespage optname-extra-notes "a"
                (_ "Notes added at end of invoice -- may contain HTML markup") 
                "Sincerely yours,<br><br><br><br>"))
                ;(N_ "(Development version -- don't rely on the numbers on this report without double-checking them.<br>Change the 'Extra Notes' option to get rid of this message)")))

  (add-option (gnc:make-text-option	notespage optname-extra-css "b"
                (N_ "Embedded CSS")	"h1.coyname { text-align: right; margin-bottom: 0px ; font-size: 200%; } h2.invoice { text-align: left; margin-bottom: 0px ; font-size: 500%; }"))
  (gnc:options-set-default-section
    report-options generalpage)

  report-options)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Create the report

(define (report-renderer report-obj)
  ;; Create and return the report as either an HTML string 
  ;; or an <html-document>
  (define (opt-value section name)
    ; wrapper for option routines
    (define (get-opt section name)
      (gnc:lookup-option (gnc:report-options report-obj) section name))
    (gnc:option-value (get-opt section name)))

  ; Get all the options
  (let* ((document                  (gnc:make-html-document))
         (opt-invoice               (opt-value generalpage  optname-invoice-number))
         (opt-template-file         (find-file 
                                      (opt-value displaypage optname-template-file)))
         (opt-css-file              (find-file 
                                      (opt-value displaypage optname-css-file)))
         (opt-heading-font          (font-name-to-style-info 
                                      (opt-value displaypage optname-heading-font)))
         (opt-text-font             (font-name-to-style-info
                                      (opt-value displaypage optname-text-font)))
         (opt-logofile              (opt-value displaypage  optname-logofile)) 
         (opt-logo-width            (opt-value displaypage  optname-logo-width)) 
         (opt-col-date              (opt-value elementspage  optname-col-date))
         (opt-col-taxrate           (opt-value elementspage  optname-col-taxrate))
         (opt-col-taxamount         (opt-value elementspage  optname-col-taxamount))
         (opt-col-netprice          (opt-value elementspage  optname-col-netprice))
         (opt-col-totalprice        (opt-value elementspage  optname-col-totalprice))
         (opt-row-taxrate           (opt-value elementspage  optname-row-taxrate))
         (opt-row-taxamount         (opt-value elementspage  optname-row-taxamount))
         (opt-row-netprice          (opt-value elementspage  optname-row-netprice))
         (opt-row-totalprice        (opt-value elementspage  optname-row-totalprice))
         (opt-row-subtotals         (opt-value elementspage  optname-row-subtotals))
         (opt-col-units             (opt-value elementspage  optname-col-units))
         (opt-row-contact-top       (opt-value elementspage  optname-row-contact-top))
         (opt-row-contact-bottom    (opt-value elementspage  optname-row-contact-bottom))
         (opt-row-address           (opt-value elementspage  optname-row-address))
         (opt-row-invoice-number    (opt-value elementspage  optname-row-invoice-number))
         (opt-row-company-name      (opt-value elementspage  optname-row-company-name))
         (opt-invnum-next-to-title  (opt-value elementspage  optname-invnum-next-to-title))
         (opt-jobname-show          (opt-value elementspage  optname-jobname-show))
         (opt-jobnumber-show        (opt-value elementspage  optname-jobnumber-show))
         (opt-report-currency       (opt-value gnc:pagename-general optname-report-currency))
         (opt-css-border-collapse   (if (opt-value displaypage optname-border-collapse) "border-collapse:collapse;"))
         (opt-css-border-color-th   (opt-value displaypage optname-border-color-th))
         (opt-css-border-color-td   (opt-value displaypage optname-border-color-td))
         (opt-report-title          (opt-value headingpage  optname-report-title))
         (opt-units-heading         (opt-value headingpage  optname-units))
         (opt-qty-heading           (opt-value headingpage  optname-qty))
         (opt-unit-price-heading    (opt-value headingpage  optname-unit-price))
         (opt-disc-rate-heading     (opt-value headingpage  optname-disc-rate))
         (opt-disc-amount-heading   (opt-value headingpage  optname-disc-amount))
         (opt-net-price-heading     (opt-value headingpage  optname-net-price))
         (opt-tax-rate-heading      (opt-value headingpage  optname-tax-rate))
         (opt-tax-amount-heading    (opt-value headingpage  optname-tax-amount))
         (opt-total-price-heading   (opt-value headingpage  optname-total-price))
         (opt-subtotal-heading      (opt-value headingpage2 optname-subtotal))
         (opt-amount-due-heading    (opt-value headingpage2 optname-amount-due))
         (opt-payment-recd-heading  (opt-value headingpage2 optname-payment-recd))
         (opt-invoice-number-text   (opt-value headingpage2 optname-invoice-number-text))
         (opt-to-text		    (opt-value headingpage2 optname-to-text))
         (opt-ref-text		    (opt-value headingpage2 optname-ref-text))
         (opt-jobnumber-text	    (opt-value headingpage2 optname-jobnumber-text))
         (opt-jobname-text	    (opt-value headingpage2 optname-jobname-text))
         (opt-extra-css             (opt-value notespage    optname-extra-css)) 
         (opt-extra-notes           (opt-value notespage    optname-extra-notes)) 
         (css? #t) ;(and (defined? 'gnc-html-engine-supports-css) (gnc-html-engine-supports-css)))
         (html #f))

    (set! html (eguile-file-to-string 
                 opt-template-file
                 (the-environment)))

    (gnc:debug "taxinvoice.scm: css? is " css?)
    (gnc:debug "taxinvoice.scm: defined is " (defined? 'gnc-html-engine-supports-css))
    (gnc:debug "taxinvoice.scm - generated html:") (gnc:debug html)

    (if css? ; return report as document or html, depending on version 
      html 
      (let ((document (gnc:make-html-document)))
        (gnc:html-document-add-object! document html)
        document))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Define the report

(gnc:define-report
  'version 1
  'name (N_ "Tax Invoice")
  'report-guid "0769e242be474010b4acf264a5512e6e"
  'menu-name (N_ "Tax Invoice")
  'menu-tip (N_ "Display a customer invoice with tax columns (using eguile template)")
  'menu-path (list gnc:menuname-business-reports)
  'options-generator options-generator
  'renderer report-renderer)

