<?xml version="1.0" encoding="UTF-8" ?>
<!-- $Header: /cvsroot/autodoc/autodoc/xml.tmpl,v 1.3 2012/01/05 15:22:28 rbt Exp $ -->
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
               "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % myent SYSTEM "entities.ent">
%myent;
]>
<book id="database.ledgersmb" xreflabel="ledgersmb database schema"><title>LederSMB 1.5.3 Model</title>




  <chapter id="public.schema"
           xreflabel="public">
    <title>Schema public</title>
    <para>standard public schema</para>


      <section id="public.table.ac-tax-form"
               xreflabel="public.ac_tax_form">
        <title id="public.table.ac-tax-form-title">
         Table:
         <database class="view">ac_tax_form</database>
         
        </title>
 

        <para>
           Mapping journal_line to country_tax_form for reporting purposes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">ac_tax_form</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reportable</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.acc-trans"
               xreflabel="public.acc_trans">
        <title id="public.table.acc-trans-title">
         Table:
         <database class="view">acc_trans</database>
         
        </title>
 

        <para>
          This table stores line items for financial transactions.  Please note that
payments in 1.3 are not full-fledged transactions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">acc_trans</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Document Source identifier for individual line items, usually used
for payments.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cleared</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">fx_transaction</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para>When &apos;f&apos;, indicates that the amount column states the amount in the currency
as specified in the associated ar, ap, payment or gl record.

When &apos;t&apos;, indicates that the amount column states the difference between
the foreighn currency amount and the base amount so that their sum equals the
base amount.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">memo</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invoice_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.invoice"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cleared_on</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reconciled_on</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">voucher_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.voucher"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on acc_trans</title>

          <varlistentry>
            <term>acc_trans_transdate_year_idx</term>
            <listitem><para>transdate, date_part(&apos;YEAR&apos;::text, transdate)) WHERE (transdate IS NOT NULL</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>acc_trans_voucher_id_idx</term>
            <listitem><para>voucher_id</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing ac_tax_form via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.ac-tax-form"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-ac"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment-links"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.tax-extended"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.account"
               xreflabel="public.account">
        <title id="public.table.account-title">
         Table:
         <database class="view">account</database>
         
        </title>
 

        <para>
           This table stores the main account info.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_temp</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

              <para> Only affects equity accounts.  If set, close at end of year. </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">category</database></term>
              <listitem><para>
                <database class="datatype">character(1)</database>



                <database class="constraint">NOT NULL</database>





              </para>

              <para> A=asset,L=liability,Q=Equity,I=Income,E=expense </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">gifi_accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">heading</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account-heading"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contra</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">tax</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">obsolete</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on account</title>

          <varlistentry>
            <term>account_category_check</term>
            <listitem><para>CHECK ((category = ANY (ARRAY[&apos;A&apos;::bpchar, &apos;L&apos;::bpchar, &apos;Q&apos;::bpchar, &apos;I&apos;::bpchar, &apos;E&apos;::bpchar])))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing acc_trans via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.acc-trans"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.account-checkpoint"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.account-link"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.account-translation"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-class"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-coa-to-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-tax"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.parts"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partstax"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-deduction-type"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-income-type"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.tax"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.account-checkpoint"
               xreflabel="public.account_checkpoint">
        <title id="public.table.account-checkpoint-title">
         Table:
         <database class="view">account_checkpoint</database>
         
        </title>
 

        <para>
           This table holds account balances at various dates.  Transactions MUST NOT
be posted prior to the latest end_date in this table, and no unapproved
transactions (vouchers or drafts) can remain in the closed period.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_checkpoint</database>
            </title>


            <varlistentry>
              <term><database class="field">end_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">debits</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">credits</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.account-heading"
               xreflabel="public.account_heading">
        <title id="public.table.account-heading-title">
         Table:
         <database class="view">account_heading</database>
         
        </title>
 

        <para>
          
This table holds the account headings in the system.  Each account must belong
to a heading, and a heading can belong to another heading.  In this way it is
possible to nest accounts for reporting purposes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_heading</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parent_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account-heading"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">category</database></term>
              <listitem><para>
                <database class="datatype">character(1)</database>







              </para>

              <para>
Same as the column account.category, except that if NULL the category
is automatically derived from the linked accounts.
</para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on account_heading</title>

          <varlistentry>
            <term>account_heading_category_check</term>
            <listitem><para>CHECK ((category = ANY (ARRAY[&apos;A&apos;::bpchar, &apos;L&apos;::bpchar, &apos;Q&apos;::bpchar, &apos;I&apos;::bpchar, &apos;E&apos;::bpchar])))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing account via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.account-heading"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.account-heading-translation"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.account-heading-derived-category"
               xreflabel="public.account_heading_derived_category">
        <title id="public.view.account-heading-derived-category-title">
         View:
         <database class="table">account_heading_derived_category</database>
         
        </title>
 

        <para>
           Lists for each row
the derived category for each heading, based on the categories of the
linked accounts.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_heading_derived_category</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parent_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">original_category</database></term>
              <listitem><para>
                <database class="datatype">character(1)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_count</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">liability_count</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">expense_count</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">income_count</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">equity_count</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">derived_category</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">category</database></term>
              <listitem><para>
                <database class="datatype">bpchar</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view account_heading_derived_category</title>
         <programlisting>
SELECT derivation.id
,
    derivation.accno
,
    derivation.description
,
    derivation.parent_id
,
    derivation.original_category
,
    derivation.asset_count
,
    derivation.liability_count
,
    derivation.expense_count
,
    derivation.income_count
,
    derivation.equity_count
,
    derivation.derived_category
,
    COALESCE
(derivation.original_category
     , (derivation.derived_category)::bpchar
) AS category
   
FROM (
SELECT category_counts.id
     ,
            category_counts.accno
     ,
            category_counts.description
     ,
            category_counts.parent_id
     ,
            category_counts.original_category
     ,
            category_counts.asset_count
     ,
            category_counts.liability_count
     ,
            category_counts.expense_count
     ,
            category_counts.income_count
     ,
            category_counts.equity_count
     ,
                CASE
                    WHEN 
     (category_counts.equity_count &gt; 0) THEN &apos;Q&apos;::text
                    WHEN 
     (
           (category_counts.income_count &gt; 0)
         AND (category_counts.expense_count &gt; 0)
     ) THEN &apos;Q&apos;::text
                    WHEN 
     (
           (category_counts.asset_count &gt; 0)
         AND (category_counts.liability_count &gt; 0)
     ) THEN &apos;Q&apos;::text
                    WHEN 
     (category_counts.asset_count &gt; 0) THEN &apos;A&apos;::text
                    WHEN 
     (category_counts.liability_count &gt; 0) THEN &apos;L&apos;::text
                    WHEN 
     (category_counts.expense_count &gt; 0) THEN &apos;E&apos;::text
                    WHEN 
     (category_counts.income_count &gt; 0) THEN &apos;I&apos;::text
                    ELSE NULL::text
                END AS derived_category
           
  FROM (
      SELECT ah.id
           ,
                    ah.accno
           ,
                    ah.description
           ,
                    ah.parent_id
           ,
                    ah.category AS original_category
           ,
                    count
           (
                        CASE
                            WHEN 
                 (acc.category = &apos;A&apos;::bpchar) THEN acc.category
                            ELSE NULL::bpchar
                        END
           ) AS asset_count
           ,
                    count
           (
                        CASE
                            WHEN 
                 (acc.category = &apos;L&apos;::bpchar) THEN acc.category
                            ELSE NULL::bpchar
                        END
           ) AS liability_count
           ,
                    count
           (
                        CASE
                            WHEN 
                 (acc.category = &apos;E&apos;::bpchar) THEN acc.category
                            ELSE NULL::bpchar
                        END
           ) AS expense_count
           ,
                    count
           (
                        CASE
                            WHEN 
                 (acc.category = &apos;I&apos;::bpchar) THEN acc.category
                            ELSE NULL::bpchar
                        END
           ) AS income_count
           ,
                    count
           (
                        CASE
                            WHEN 
                 (acc.category = &apos;Q&apos;::bpchar) THEN acc.category
                            ELSE NULL::bpchar
                        END
           ) AS equity_count
                   
        FROM (
                 (account_heading_descendant ahd
                     
                    JOIN account_heading ah 
                      ON (
                             (ahd.id = ah.id)
                       )
                 )
                     
         LEFT JOIN account acc 
                ON (
                       (ahd.descendant_id = acc.heading)
                 )
           )
                  
    GROUP BY ah.id
           , ah.accno
           , ah.description
           , ah.parent_id
           , ah.category
     ) category_counts
) derivation;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.view.account-heading-descendant"
               xreflabel="public.account_heading_descendant">
        <title id="public.view.account-heading-descendant-title">
         View:
         <database class="table">account_heading_descendant</database>
         
        </title>
 

        <para>
           Returns rows for
each heading listing its immediate children, children of children, etc., etc.

This is primarily practical when calculating subtotals
for PNL and B/S headings.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_heading_descendant</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">level</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">descendant_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">descendant_accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view account_heading_descendant</title>
         <programlisting> WITH RECURSIVE account_headings AS 
(
         
SELECT account_heading.id
     ,
            1 AS level
     ,
            account_heading.id AS descendant_id
     ,
            account_heading.accno
     ,
            account_heading.accno AS descendant_accno
           
  FROM account_heading
        
UNION ALL
         
SELECT at.id
     ,
            
     (at.level + 1) AS level
     ,
            ah.id AS descendant_id
     ,
            at.accno
     ,
            ah.accno AS descendant_accno
           
  FROM (account_heading ah
             
        JOIN account_headings at 
          ON (
                 (ah.parent_id = at.descendant_id)
           )
     )
        
)
 
SELECT account_headings.id
,
    account_headings.level
,
    account_headings.descendant_id
,
    account_headings.accno
,
    account_headings.descendant_accno
   
FROM account_headings;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.account-heading-translation"
               xreflabel="public.account_heading_translation">
        <title id="public.table.account-heading-translation-title">
         Table:
         <database class="view">account_heading_translation</database>
         
        </title>
 

        <para>
          Translations for account heading descriptions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_heading_translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.account-heading"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.account-heading-tree"
               xreflabel="public.account_heading_tree">
        <title id="public.view.account-heading-tree-title">
         View:
         <database class="table">account_heading_tree</database>
         
        </title>
 

        <para>
           Returns in the &apos;path&apos; field an
array which contains the path of the heading to its associated root.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_heading_tree</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">level</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">path</database></term>
              <listitem><para>
                <database class="datatype">integer[]</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view account_heading_tree</title>
         <programlisting> WITH RECURSIVE account_headings AS 
(
         
SELECT account_heading.id
     ,
            account_heading.accno
     ,
            account_heading.description
     ,
            1 AS level
     ,
            ARRAY[account_heading.id] AS path
           
  FROM account_heading
          
 WHERE (account_heading.parent_id IS NULL)
        
UNION ALL
         
SELECT ah.id
     ,
            ah.accno
     ,
            ah.description
     ,
            
     (at.level + 1) AS level
     ,
            array_append
     (at.path
           , ah.id
     ) AS path
           
  FROM (account_heading ah
             
        JOIN account_headings at 
          ON (
                 (ah.parent_id = at.id)
           )
     )
        
)
 
SELECT account_headings.id
,
    account_headings.accno
,
    account_headings.description
,
    account_headings.level
,
    account_headings.path
   
FROM account_headings;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.account-link"
               xreflabel="public.account_link">
        <title id="public.table.account-link-title">
         Table:
         <database class="view">account_link</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_link</database>
            </title>


            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account-link-description"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.account-link-description"
               xreflabel="public.account_link_description">
        <title id="public.table.account-link-description-title">
         Table:
         <database class="view">account_link_description</database>
         
        </title>
 

        <para>
           This is a lookup table which provide basic information as to categories and
dropdowns of accounts.  In general summary accounts cannot belong to more than
one category (an AR summary account cannot appear in other dropdowns for
example).  Custom fields are not overwritten when the account is edited from
the front-end.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_link_description</database>
            </title>


            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">summary</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">custom</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing account_link via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.account-link"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-line"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.account-translation"
               xreflabel="public.account_translation">
        <title id="public.table.account-translation-title">
         Table:
         <database class="view">account_translation</database>
         
        </title>
 

        <para>
          Translations for account descriptions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">account_translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.ap"
               xreflabel="public.ap">
        <title id="public.table.ap-title">
         Table:
         <database class="view">ap</database>
         
        </title>
 

        <para>
           Summary/header information for AP transactions and vendor invoices.
Note that some constraints here are hard to enforce because we haven not gotten
to rewriting the relevant code here.
HV TODO drop entity_id

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">ap</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;id&apos;::regclass)</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> Text identifier for the invoice.  Must be unique.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxincluded</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para> This stores the total amount (including taxes) for the transaction.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">netamount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para> Total amount excluding taxes for the transaction.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">paid</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">datepaid</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">duedate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invoice</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> True if the transaction tracks goods/services purchase using the invoice
table.  False otherwise.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ordnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> Order Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

              <para> 3 letters to identify the currency.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>These notes are displayed on the invoice when printed or emailed</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

              <para>Person who created the transaction</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">till</database></term>
              <listitem><para>
                <database class="datatype">character varying(20)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">quonumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Quotation Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">intnotes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>These notes are not displayed when the invoice is printed or emailed and
may be updated without reposting hte invocie.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shipvia</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ponumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Purchase Order Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shippingpoint</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">on_hold</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

              <para>Only show in financial reports if true.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reverse</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para>If true numbers are displayed after multiplying by -1</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">terms</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">force_closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

              <para> Not exposed to the UI, but can be set to prevent an invoice from showing up
for payment or in outstanding reports.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">crdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_return</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_account</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

              <para> reference for the vendor account used.</para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on ap</title>

          <varlistentry>
            <term>ap_check</term>
            <listitem><para>CHECK ((((amount IS NULL) AND (curr IS NULL)) OR ((amount IS NOT NULL) AND (curr IS NOT NULL))))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.ar"
               xreflabel="public.ar">
        <title id="public.table.ar-title">
         Table:
         <database class="view">ar</database>
         
        </title>
 

        <para>
           Summary/header information for AR transactions and sales invoices.
Note that some constraints here are hard to enforce because we haven not gotten
to rewriting the relevant code here.
HV TODO drop entity_id

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">ar</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;id&apos;::regclass)</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> Text identifier for the invoice.  Must be unique.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxincluded</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para> This stores the total amount (including taxes) for the transaction.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">netamount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para> Total amount excluding taxes for the transaction.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">paid</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">datepaid</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">duedate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invoice</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> True if the transaction tracks goods/services purchase using the invoice
table.  False otherwise.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shippingpoint</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">terms</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>These notes are displayed on the invoice when printed or emailed</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

              <para> 3 letters to identify the currency.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ordnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> Order Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

              <para>Person who created the transaction</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">till</database></term>
              <listitem><para>
                <database class="datatype">character varying(20)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">quonumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Quotation Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">intnotes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>These notes are not displayed when the invoice is printed or emailed and
may be updated without reposting hte invocie.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shipvia</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ponumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Purchase Order Number</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">on_hold</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reverse</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para>If true numbers are displayed after multiplying by -1</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

              <para>Only show in financial reports if true.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_account</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

              <para> reference for the customer account used.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">force_closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

              <para> Not exposed to the UI, but can be set to prevent an invoice from showing up
for payment or in outstanding reports.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_return</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">crdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">setting_sequence</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on ar</title>

          <varlistentry>
            <term>ar_check</term>
            <listitem><para>CHECK ((((amount IS NULL) AND (curr IS NULL)) OR ((amount IS NOT NULL) AND (curr IS NOT NULL))))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>ar_check1</term>
            <listitem><para>CHECK (((invnumber IS NOT NULL) OR (NOT approved)))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.assembly"
               xreflabel="public.assembly">
        <title id="public.table.assembly-title">
         Table:
         <database class="view">assembly</database>
         
        </title>
 

        <para>
          Holds mapping for parts that are members of assemblies.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">assembly</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>




              </para>

              <para>This is the id of the assembly the part is being mapped to.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>




              </para>

              <para>ID of part that is a member of the assembly.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bom</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">adj</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on assembly</title>

          <varlistentry>
            <term>assembly_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.asset-class"
               xreflabel="public.asset_class">
        <title id="public.table.asset-class-title">
         Table:
         <database class="view">asset_class</database>
         
        </title>
 

        <para>
          
The account fields here set the defaults for the individual asset items.  They
are non-authoritative.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dep_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">method</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.asset-dep-method"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-report"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-dep-method"
               xreflabel="public.asset_dep_method">
        <title id="public.table.asset-dep-method-title">
         Table:
         <database class="view">asset_dep_method</database>
         
        </title>
 

        <para>
           Stores asset depreciation methods, and their relevant stored procedures.

The fixed asset system is such depreciation methods can be plugged in via this
table.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_dep_method</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">method</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> These are keyed to specific stored procedures.  Currently only &quot;straight_line&quot; is supported</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sproc</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

              <para>The sproc mentioned here is a stored procedure which must have the following
arguments: (in_asset_ids int[],  in_report_date date, in_report_id int).

Here in_asset_ids are the assets to be depreciated, in_report_date is the date
of the report, and in_report_id is the id of the report.  The sproc MUST
insert the relevant lines into asset_report_line. </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit_label</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">short_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.asset-unit-class"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_class via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-class"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-disposal-method"
               xreflabel="public.asset_disposal_method">
        <title id="public.table.asset-disposal-method-title">
         Table:
         <database class="view">asset_disposal_method</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_disposal_method</database>
            </title>


            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">multiple</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">short_label</database></term>
              <listitem><para>
                <database class="datatype">character(1)</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on asset_disposal_method</title>

          <varlistentry>
            <term>asset_disposal_method_multiple_check</term>
            <listitem><para>CHECK ((multiple = ANY (ARRAY[1, 0, &apos;-1&apos;::integer])))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_rl_to_disposal_method via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-rl-to-disposal-method"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-item"
               xreflabel="public.asset_item">
        <title id="public.table.asset-item-title">
         Table:
         <database class="view">asset_item</database>
         
        </title>
 

        <para>
           Stores details of asset items.  The account fields here are authoritative,
while the ones in the asset_class table are defaults.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_item</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">tag</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

              <para> This can be plugged into other routines to generate it automatically via ALTER TABLE .... SET DEFAULT.....</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">purchase_value</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">salvage_value</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">usable_life</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">purchase_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">start_depreciation</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">location_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.warehouse"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">department_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invoice_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.eca-invoice"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dep_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">exp_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">obsolete_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE#1</database>









                <database class="constraint">REFERENCES <xref linkend="public.table.asset-item"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.asset-class"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-note"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-rl-to-disposal-method"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-note"
               xreflabel="public.asset_note">
        <title id="public.table.asset-note-title">
         Table:
         <database class="view">asset_note</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT 4</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.asset-item"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on asset_note</title>

          <varlistentry>
            <term>asset_note_note_class_check</term>
            <listitem><para>CHECK ((note_class = 4))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.asset-report"
               xreflabel="public.asset_report">
        <title id="public.table.asset-report-title">
         Table:
         <database class="view">asset_report</database>
         
        </title>
 

        <para>
           Asset reports are discrete sets of depreciation or disposal transctions,
and each one may be turned into no more than one GL transaction.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_report</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">gl_id</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>








                <database class="constraint">UNIQUE</database>









                <database class="constraint">REFERENCES <xref linkend="public.table.gl"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_class</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.asset-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.asset-report-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_by</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT person__get_my_entity_id()</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">depreciated_qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dont_approve</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">submitted</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_report_line via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-rl-to-disposal-method"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-report-class"
               xreflabel="public.asset_report_class">
        <title id="public.table.asset-report-class-title">
         Table:
         <database class="view">asset_report_class</database>
         
        </title>
 

        <para>
            By default only four types of asset reports are supported.  In the future
others may be added.  Please correspond on the list before adding more types.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_report_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_report via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-report"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.asset-report-line"
               xreflabel="public.asset_report_line">
        <title id="public.table.asset-report-line-title">
         Table:
         <database class="view">asset_report_line</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_report_line</database>
            </title>


            <varlistentry>
              <term><database class="field">asset_id</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.asset-item"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.asset-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">department_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

              <para> In case assets are moved between departments, we have to store this here.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">warehouse_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.warehouse"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.asset-rl-to-disposal-method"
               xreflabel="public.asset_rl_to_disposal_method">
        <title id="public.table.asset-rl-to-disposal-method-title">
         Table:
         <database class="view">asset_rl_to_disposal_method</database>
         
        </title>
 

        <para>
           Maps disposal method to line items in the asset disposal report.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_rl_to_disposal_method</database>
            </title>


            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.asset-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">asset_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.asset-item"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">disposal_method_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.asset-disposal-method"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">percent_disposed</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.asset-unit-class"
               xreflabel="public.asset_unit_class">
        <title id="public.table.asset-unit-class-title">
         Table:
         <database class="view">asset_unit_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">asset_unit_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_dep_method via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-dep-method"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.audittrail"
               xreflabel="public.audittrail">
        <title id="public.table.audittrail-title">
         Table:
         <database class="view">audittrail</database>
         
        </title>
 

        <para>
           This stores information on who entered or updated rows in the ar, ap, or gl
tables.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">audittrail</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">tablename</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">formname</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">action</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">bigserial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on audittrail</title>

          <varlistentry>
            <term>audittrail_trans_id_key</term>
            <listitem><para>trans_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.batch"
               xreflabel="public.batch">
        <title id="public.table.batch-title">
         Table:
         <database class="view">batch</database>
         
        </title>
 

        <para>
           Stores batch header info.  Batches are groups of vouchers that are posted
together.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">batch</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">batch_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.batch-class"/></database>


              </para>

              <para> Note that this field is largely used for sorting the vouchers.  A given batch is NOT restricted to this type.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">control_code</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">default_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_on</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">locked_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.session"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_on</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on batch</title>

          <varlistentry>
            <term>batch_control_code_check</term>
            <listitem><para>CHECK ((length(control_code) &gt; 0))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing voucher via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.voucher"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.batch-class"
               xreflabel="public.batch_class">
        <title id="public.table.batch-class-title">
         Table:
         <database class="view">batch_class</database>
         
        </title>
 

        <para>
           These values are hard-coded.  Please coordinate before adding standard
values. Values from 900 to 999 are reserved for local use.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">batch_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing batch via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.batch"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.voucher"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.bu-class-to-module"
               xreflabel="public.bu_class_to_module">
        <title id="public.table.bu-class-to-module-title">
         Table:
         <database class="view">bu_class_to_module</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">bu_class_to_module</database>
            </title>


            <varlistentry>
              <term><database class="field">bu_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">module_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.lsmb-module"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.budget-info"
               xreflabel="public.budget_info">
        <title id="public.table.budget-info-title">
         Table:
         <database class="view">budget_info</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">budget_info</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">start_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">end_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT person__get_my_entity_id()</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">obsolete_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">obsolete_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on budget_info</title>

          <varlistentry>
            <term>budget_info_check</term>
            <listitem><para>CHECK ((start_date &lt; end_date))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing budget_line via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.budget-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-note"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-to-business-unit"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.budget-line"
               xreflabel="public.budget_line">
        <title id="public.table.budget-line-title">
         Table:
         <database class="view">budget_line</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">budget_line</database>
            </title>


            <varlistentry>
              <term><database class="field">budget_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.budget-info"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.budget-note"
               xreflabel="public.budget_note">
        <title id="public.table.budget-note-title">
         Table:
         <database class="view">budget_note</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">budget_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT 6</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.budget-info"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on budget_note</title>

          <varlistentry>
            <term>budget_note_note_class_check</term>
            <listitem><para>CHECK ((note_class = 6))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.budget-to-business-unit"
               xreflabel="public.budget_to_business_unit">
        <title id="public.table.budget-to-business-unit-title">
         Table:
         <database class="view">budget_to_business_unit</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">budget_to_business_unit</database>
            </title>


            <varlistentry>
              <term><database class="field">budget_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE</database>



                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.budget-info"/></database>






              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.business"
               xreflabel="public.business">
        <title id="public.table.business-title">
         Table:
         <database class="view">business</database>
         
        </title>
 

        <para>
          Groups of Customers assigned joint discounts.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.business-unit"
               xreflabel="public.business_unit">
        <title id="public.table.business-unit-title">
         Table:
         <database class="view">business_unit</database>
         
        </title>
 

        <para>
           Tracks Projects, Departments, Funds, Etc.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE#1</database>



                <database class="constraint">PRIMARY KEY</database>














              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE#2</database>









                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>








                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">control_code</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE#2</database>










              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">start_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">end_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parent_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-to-business-unit"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-ac"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-inv"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-jl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-oitem"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-translation"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.jcitems"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.job"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.business-unit-ac"
               xreflabel="public.business_unit_ac">
        <title id="public.table.business-unit-ac-title">
         Table:
         <database class="view">business_unit_ac</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_ac</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>










                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>



                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on business_unit_ac</title>

          <varlistentry>
            <term>business_unit_ac_entry_id_idx</term>
            <listitem><para>entry_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.business-unit-class"
               xreflabel="public.business_unit_class">
        <title id="public.table.business-unit-class-title">
         Table:
         <database class="view">business_unit_class</database>
         
        </title>
 

        <para>
           Consolidates projects and departments, and allows this to be extended for
funds accounting and other purposes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">active</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ordering</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing bu_class_to_module via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.bu-class-to-module"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-to-business-unit"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-ac"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-inv"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-jl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-oitem"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.business-unit-inv"
               xreflabel="public.business_unit_inv">
        <title id="public.table.business-unit-inv-title">
         Table:
         <database class="view">business_unit_inv</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_inv</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.invoice"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>










                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>



                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on business_unit_inv</title>

          <varlistentry>
            <term>business_unit_inv_entry_id_idx</term>
            <listitem><para>entry_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.business-unit-jl"
               xreflabel="public.business_unit_jl">
        <title id="public.table.business-unit-jl-title">
         Table:
         <database class="view">business_unit_jl</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_jl</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.journal-line"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.business-unit-oitem"
               xreflabel="public.business_unit_oitem">
        <title id="public.table.business-unit-oitem-title">
         Table:
         <database class="view">business_unit_oitem</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_oitem</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.orderitems"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>










                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit-class"/></database>



                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on business_unit_oitem</title>

          <varlistentry>
            <term>business_unit_oitem_entry_id_idx</term>
            <listitem><para>entry_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.business-unit-translation"
               xreflabel="public.business_unit_translation">
        <title id="public.table.business-unit-translation-title">
         Table:
         <database class="view">business_unit_translation</database>
         
        </title>
 

        <para>
           Translation information for projects, departments, etc.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">business_unit_translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.cash-impact"
               xreflabel="public.cash_impact">
        <title id="public.view.cash-impact-title">
         View:
         <database class="table">cash_impact</database>
         
        </title>
 

        <para>
           This view is used by cash basis reports to determine the fraction of a
transaction to be counted.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">cash_impact</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">portion</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rel</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view cash_impact</title>
         <programlisting>
SELECT gl.id
,
    &apos;1&apos;::numeric AS portion
,
    &apos;gl&apos;::text AS rel
,
    gl.transdate
   
FROM gl

UNION ALL
 
SELECT gl.id
,
        CASE
            WHEN 
(gl.amount = 
     (0)::numeric
) THEN 
(0)::numeric
            WHEN 
(gl.transdate = ac.transdate) THEN 
(
     (1)::numeric + 
     (sum
           (ac.amount) / gl.amount
     )
)
            ELSE 
(
     (1)::numeric - 
     (
           (gl.amount - sum
                 (ac.amount)
           ) / gl.amount
     )
)
        END AS portion
,
    &apos;ar&apos;::text AS rel
,
    ac.transdate
   
FROM (
     (ar gl
     
        JOIN acc_trans ac 
          ON (
                 (ac.trans_id = gl.id)
           )
     )
     
  JOIN account_link al 
    ON (
           (
                 (ac.chart_id = al.account_id)
               AND (al.description = &apos;AR&apos;::text)
           )
     )
)
  
GROUP BY gl.id
, gl.amount
, ac.transdate
, gl.transdate

UNION ALL
 
SELECT gl.id
,
        CASE
            WHEN 
(gl.amount = 
     (0)::numeric
) THEN 
(0)::numeric
            WHEN 
(gl.transdate = ac.transdate) THEN 
(
     (1)::numeric - 
     (sum
           (ac.amount) / gl.amount
     )
)
            ELSE 
(
     (1)::numeric - 
     (
           (gl.amount + sum
                 (ac.amount)
           ) / gl.amount
     )
)
        END AS portion
,
    &apos;ap&apos;::text AS rel
,
    ac.transdate
   
FROM (
     (ap gl
     
        JOIN acc_trans ac 
          ON (
                 (ac.trans_id = gl.id)
           )
     )
     
  JOIN account_link al 
    ON (
           (
                 (ac.chart_id = al.account_id)
               AND (al.description = &apos;AP&apos;::text)
           )
     )
)
  
GROUP BY gl.id
, gl.amount
, ac.transdate
, gl.transdate;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.view.chart"
               xreflabel="public.chart">
        <title id="public.view.chart-title">
         View:
         <database class="table">chart</database>
         
        </title>
 

        <para>
          Compatibility chart for 1.2 and earlier.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">chart</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">charttype</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">category</database></term>
              <listitem><para>
                <database class="datatype">bpchar</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">link</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_heading</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">gifi_accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contra</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">tax</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view chart</title>
         <programlisting>
SELECT ah.id
,
    ah.accno
,
    COALESCE
(ht.description
     , ah.description
) AS description
,
    &apos;H&apos;::text AS charttype
,
    NULL::bpchar AS category
,
    NULL::text AS link
,
    ah.parent_id AS account_heading
,
    NULL::text AS gifi_accno
,
    false AS contra
,
    false AS tax
   
FROM (account_heading ah
     
LEFT JOIN (
      SELECT ht_1.trans_id
           ,
            ht_1.description
           
        FROM (
                 (account_heading_translation ht_1
             
                    JOIN user_preference up 
                      ON (
                             (
                                   (up.language)::text = 
                                   (ht_1.language_code)::text
                             )
                       )
                 )
             
              JOIN users 
                ON (
                       (up.id = users.id)
                 )
           )
          
       WHERE (
                 (users.username)::name = &quot;session_user&quot;
                 ()
           )
     ) ht 
    ON (
           (ah.id = ht.trans_id)
     )
)
UNION
 
SELECT c.id
,
    c.accno
,
    COALESCE
(at.description
     , c.description
) AS description
,
    &apos;A&apos;::text AS charttype
,
    c.category
,
    concat_colon
(l.description) AS link
,
    c.heading AS account_heading
,
    c.gifi_accno
,
    c.contra
,
    c.tax
   
FROM (
     (account c
     
   LEFT JOIN account_link l 
          ON (
                 (c.id = l.account_id)
           )
     )
     
LEFT JOIN (
      SELECT at_1.trans_id
           ,
            at_1.description
           
        FROM (
                 (account_translation at_1
             
                    JOIN user_preference up 
                      ON (
                             (
                                   (up.language)::text = 
                                   (at_1.language_code)::text
                             )
                       )
                 )
             
              JOIN users 
                ON (
                       (up.id = users.id)
                 )
           )
          
       WHERE (
                 (users.username)::name = &quot;session_user&quot;
                 ()
           )
     ) at 
    ON (
           (c.id = at.trans_id)
     )
)
  
GROUP BY c.id
, c.accno
, COALESCE
(at.description
     , c.description
)
, c.category
, c.heading
, c.gifi_accno
, c.contra
, c.tax;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.company"
               xreflabel="public.company">
        <title id="public.table.company-title">
         Table:
         <database class="view">company</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">company</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">legal_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">tax_id</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> In the US this would be a EIN. </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sales_tax_id</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">license_number</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sic_code</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on company</title>

          <varlistentry>
            <term>company_legal_name_check</term>
            <listitem><para>CHECK ((legal_name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing person_to_company via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.person-to-company"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.contact-class"
               xreflabel="public.contact_class">
        <title id="public.table.contact-class-title">
         Table:
         <database class="view">contact_class</database>
         
        </title>
 

        <para>
           Stores type of contact information attached to companies and persons.
Please coordinate with others before adding new types.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">contact_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on contact_class</title>

          <varlistentry>
            <term>contact_class_class_check</term>
            <listitem><para>CHECK ((class ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing eca_to_contact via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.eca-to-contact"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-to-contact"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.country"
               xreflabel="public.country">
        <title id="public.table.country-title">
         Table:
         <database class="view">country</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">country</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">name</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">short_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">itu</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> The ITU Telecommunication Standardization Sector code for calling internationally. For example, the US is 1, Great Britain is 44 </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on country</title>

          <varlistentry>
            <term>country_name_check</term>
            <listitem><para>CHECK ((name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>country_short_name_check</term>
            <listitem><para>CHECK ((short_name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing country_tax_form via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.country-tax-form"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-deduction-class"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-income-class"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.country-tax-form"
               xreflabel="public.country_tax_form">
        <title id="public.table.country-tax-form-title">
         Table:
         <database class="view">country_tax_form</database>
         
        </title>
 

        <para>
           This table was designed for holding information relating to reportable
sales or purchases, such as IRS 1099 forms and international equivalents.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">country_tax_form</database>
            </title>


            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.country"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">form_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">default_reportable</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_accrual</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing entity_credit_account via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.cr-coa-to-account"
               xreflabel="public.cr_coa_to_account">
        <title id="public.table.cr-coa-to-account-title">
         Table:
         <database class="view">cr_coa_to_account</database>
         
        </title>
 

        <para>
           Provides name mapping for the cash reconciliation screen.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">cr_coa_to_account</database>
            </title>


            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.cr-report"
               xreflabel="public.cr_report">
        <title id="public.table.cr-report-title">
         Table:
         <database class="view">cr_report</database>
         
        </title>
 

        <para>
          This table holds header data for cash reports.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">cr_report</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">bigserial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">their_total</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">submitted</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">end_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">updated</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT person__get_my_entity_id()</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_username</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">deleted</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">deleted_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_username</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">recon_fx</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">max_ac_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on cr_report</title>

          <varlistentry>
            <term>cr_report_check</term>
            <listitem><para>CHECK (((deleted IS NOT TRUE) OR (approved IS NOT TRUE)))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing cr_report_line via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.cr-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-line"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.cr-report-line"
               xreflabel="public.cr_report_line">
        <title id="public.table.cr-report-line-title">
         Table:
         <database class="view">cr_report_line</database>
         
        </title>
 

        <para>
           This stores line item data on transaction lines and whether they are
cleared.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">cr_report_line</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">bigserial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.cr-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">scn</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> This is the check number.  Maps to gl.reference </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">their_balance</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">our_balance</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">errorcode</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">user</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">clear_time</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">insert_time</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_type</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">post_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ledger_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">voucher_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">overlook</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cleared</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.custom-field-catalog"
               xreflabel="public.custom_field_catalog">
        <title id="public.table.custom-field-catalog-title">
         Table:
         <database class="view">custom_field_catalog</database>
         
        </title>
 

        <para>
           Deprecated, all use removed from old code.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">custom_field_catalog</database>
            </title>


            <varlistentry>
              <term><database class="field">field_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">table_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.custom-table-catalog"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">field_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.custom-table-catalog"
               xreflabel="public.custom_table_catalog">
        <title id="public.table.custom-table-catalog-title">
         Table:
         <database class="view">custom_table_catalog</database>
         
        </title>
 

        <para>
           Deprecated, all use removed from old code.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">custom_table_catalog</database>
            </title>


            <varlistentry>
              <term><database class="field">table_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">extends</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">table_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing custom_field_catalog via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.custom-field-catalog"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.db-patch-log"
               xreflabel="public.db_patch_log">
        <title id="public.table.db-patch-log-title">
         Table:
         <database class="view">db_patch_log</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">db_patch_log</database>
            </title>


            <varlistentry>
              <term><database class="field">when_applied</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">path</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sha</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sqlstate</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">error</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.db-patches"
               xreflabel="public.db_patches">
        <title id="public.table.db-patches-title">
         Table:
         <database class="view">db_patches</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">db_patches</database>
            </title>


            <varlistentry>
              <term><database class="field">sha</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">path</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_updated</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.defaults"
               xreflabel="public.defaults">
        <title id="public.table.defaults-title">
         Table:
         <database class="view">defaults</database>
         
        </title>
 

        <para>
            This is a free-form table for managing application settings per company
database.  We use key-value modelling here because this most accurately maps
the actual semantics of the data.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">defaults</database>
            </title>


            <varlistentry>
              <term><database class="field">setting_key</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">value</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing lsmb_sequence via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.lsmb-sequence"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.eca-invoice"
               xreflabel="public.eca_invoice">
        <title id="public.table.eca-invoice-title">
         Table:
         <database class="view">eca_invoice</database>
         
        </title>
 

        <para>
           Replaces the rest of the ar and ap tables.
Also tracks payments and receipts. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">eca_invoice</database>
            </title>


            <varlistentry>
              <term><database class="field">order_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

              <para> Link to order it was created from</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">journal_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.journal-entry"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">on_hold</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> On hold invoices can not be paid, and overpayments that are on hold cannot
be used to pay invoices.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reverse</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> When this is set to true, the invoice is shown with opposite normal numbers,
i.e. negatives appear as positives, and positives appear as negatives.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">due</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character(6)</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.language"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">force_closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

              <para> When this is set to true, the invoice does not show up on outstanding reports
and cannot be paid.  Overpayments where this is set to true do not appear on
outstanding reports and cannot be paid.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">order_number</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> This is the order number of the other party.  So for a sales invoice, this
would be a purchase order, and for a vendor invoice, this would be a sales
order.</para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment-map"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.eca-note"
               xreflabel="public.eca_note">
        <title id="public.table.eca-note-title">
         Table:
         <database class="view">eca_note</database>
         
        </title>
 

        <para>
           Notes for entity_credit_account entries.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">eca_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

              <para> references entity_credit_account.id</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on eca_note</title>

          <varlistentry>
            <term>eca_note_note_class_check</term>
            <listitem><para>CHECK ((note_class = 3))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.eca-tax"
               xreflabel="public.eca_tax">
        <title id="public.table.eca-tax-title">
         Table:
         <database class="view">eca_tax</database>
         
        </title>
 

        <para>
           Mapping customers and vendors to taxes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">eca_tax</database>
            </title>


            <varlistentry>
              <term><database class="field">eca_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.eca-to-contact"
               xreflabel="public.eca_to_contact">
        <title id="public.table.eca-to-contact-title">
         Table:
         <database class="view">eca_to_contact</database>
         
        </title>
 

        <para>
           To keep track of the relationship between multiple contact methods and a single vendor or customer account. For generic
contacts, use entity_to_contact instead.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">eca_to_contact</database>
            </title>


            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contact_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.contact-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contact</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on eca_to_contact</title>

          <varlistentry>
            <term>eca_to_contact_contact_check</term>
            <listitem><para>CHECK ((contact ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.eca-to-location"
               xreflabel="public.eca_to_location">
        <title id="public.table.eca-to-location-title">
         Table:
         <database class="view">eca_to_location</database>
         
        </title>
 

        <para>
           This table is used for locations bound to contracts.  For generic contact
addresses, use entity_to_location instead 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">eca_to_location</database>
            </title>


            <varlistentry>
              <term><database class="field">location_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.location"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">location_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.location-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.employee-class"
               xreflabel="public.employee_class">
        <title id="public.table.employee-class-title">
         Table:
         <database class="view">employee_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">employee_class</database>
            </title>


            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing employee_to_ec via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.employee-to-ec"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.employee-search"
               xreflabel="public.employee_search">
        <title id="public.view.employee-search-title">
         View:
         <database class="table">employee_search</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">employee_search</database>
            </title>


            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">startdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">enddate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">role</database></term>
              <listitem><para>
                <database class="datatype">character varying(20)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ssn</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sales</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">manager_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employeenumber</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dob</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_manager</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">manager</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view employee_search</title>
         <programlisting>
SELECT e.entity_id
,
    e.startdate
,
    e.enddate
,
    e.role
,
    e.ssn
,
    e.sales
,
    e.manager_id
,
    e.employeenumber
,
    e.dob
,
    e.is_manager
,
    em.name AS manager
,
    emn.note
,
    en.name
   
FROM (
     (
           (
                 (entity_employee e
     
               LEFT JOIN entity en 
                      ON (
                             (e.entity_id = en.id)
                       )
                 )
     
         LEFT JOIN entity_employee m 
                ON (
                       (e.manager_id = m.entity_id)
                 )
           )
     
   LEFT JOIN entity em 
          ON (
                 (em.id = m.entity_id)
           )
     )
     
LEFT JOIN entity_note emn 
    ON (
           (emn.ref_key = em.id)
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.employee-to-ec"
               xreflabel="public.employee_to_ec">
        <title id="public.table.employee-to-ec-title">
         Table:
         <database class="view">employee_to_ec</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">employee_to_ec</database>
            </title>


            <varlistentry>
              <term><database class="field">employee_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ec_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.employee-class"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.employees"
               xreflabel="public.employees">
        <title id="public.view.employees-title">
         View:
         <database class="table">employees</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">employees</database>
            </title>


            <varlistentry>
              <term><database class="field">salutation</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">first_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">startdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">enddate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">role</database></term>
              <listitem><para>
                <database class="datatype">character varying(20)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ssn</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sales</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">manager_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employeenumber</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dob</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_manager</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view employees</title>
         <programlisting>
SELECT s.salutation
,
    p.first_name
,
    p.last_name
,
    ee.entity_id
,
    ee.startdate
,
    ee.enddate
,
    ee.role
,
    ee.ssn
,
    ee.sales
,
    ee.manager_id
,
    ee.employeenumber
,
    ee.dob
,
    ee.is_manager
   
FROM (
     (person p
     
        JOIN entity_employee ee 
       USING (entity_id)
     )
     
LEFT JOIN salutation s 
    ON (
           (p.salutation_id = s.id)
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.entity"
               xreflabel="public.entity">
        <title id="public.table.entity-title">
         Table:
         <database class="view">entity</database>
         
        </title>
 

        <para>
           The primary entity table to map to all contacts 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> This is the common name of an entity. If it was a person it may be Joshua Drake, a company Acme Corp. You may also choose to use a domain such as commandprompt.com </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>










                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-class"/></database>



                <database class="constraint">REFERENCES <xref linkend="public.table.entity-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">control_code</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE</database>



                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT setting_increment(&apos;entity_control&apos;::character varying)</literal>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.country"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity</title>

          <varlistentry>
            <term>entity_name_check</term>
            <listitem><para>CHECK ((name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing ap via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.ap"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.ar"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.budget-info"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.company"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.cr-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-bank-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-employee"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-note"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-other-name"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-to-contact"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-base"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-entity"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-secondary-attachment"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-entry"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.oe"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-deduction"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-paid-timeoff"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-wage"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.person"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.robot"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.transactions"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.users"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.entity-bank-account"
               xreflabel="public.entity_bank_account">
        <title id="public.table.entity-bank-account-title">
         Table:
         <database class="view">entity_bank_account</database>
         
        </title>
 

        <para>
          This stores bank account information for both companies and persons.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_bank_account</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bic</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> Banking Institution Code, such as routing number of SWIFT code.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">iban</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> International Bank Account Number.  used to store the actual account number
for the banking institution.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">remark</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>







              </para>

              <para> This field contains the notes for an account, like: This is USD account, this one is HUF account, this one is the default account, this account for paying specific taxes. If a $
</para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing entity_credit_account via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.entity-class"
               xreflabel="public.entity_class">
        <title id="public.table.entity-class-title">
         Table:
         <database class="view">entity_class</database>
         
        </title>
 

        <para>
           Defines the class type such as vendor, customer, contact, employee 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> The first 7 values are reserved and
permanent.  Individuals who create new classes, however, should coordinate
with others for ranges to use.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">active</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity_class</title>

          <varlistentry>
            <term>entity_class_class_check</term>
            <listitem><para>CHECK ((class ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on entity_class</title>

          <varlistentry>
            <term>entity_class_idx</term>
            <listitem><para>lower(class)</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing entity via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.entity"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.location-class-to-entity-class"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.entity-credit-account"
               xreflabel="public.entity_credit_account">
        <title id="public.table.entity-credit-account-title">
         Table:
         <database class="view">entity_credit_account</database>
         
        </title>
 

        <para>
          This table stores information relating to general relationships regarding
moneys owed on invoice.  Invoices, whether AR or AP, must be attached to
a record in this table.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_credit_account</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pay_to_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount_terms</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxincluded</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">creditlimit</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">terms</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">meta_number</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> This stores the human readable control code for the customer/vendor record.
This is typically called the customer/vendor &quot;account&quot; in the application.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">business_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>









                <literal>DEFAULT &apos;en&apos;::character varying</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.language"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pricegroup_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.pricegroup"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">startdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">enddate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">threshold</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employee_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">primary_contact</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ar_ap_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cash_account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bank_account</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-bank-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxform_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.country-tax-form"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity_credit_account</title>

          <varlistentry>
            <term>entity_credit_account_check</term>
            <listitem><para>CHECK (((ar_ap_account_id IS NOT NULL) OR (entity_id = 0)))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>entity_credit_account_entity_class_check</term>
            <listitem><para>CHECK ((entity_class = ANY (ARRAY[1, 2])))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing ap via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.ap"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.ar"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-invoice"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-note"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-tax"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-to-contact"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.eca-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-eca"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.oe"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partscustomer"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partsvendor"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.entity-employee"
               xreflabel="public.entity_employee">
        <title id="public.table.entity-employee-title">
         Table:
         <database class="view">entity_employee</database>
         
        </title>
 

        <para>
           This contains employee-specific extensions to person/entity. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_employee</database>
            </title>


            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">startdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">enddate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">role</database></term>
              <listitem><para>
                <database class="datatype">character varying(20)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ssn</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sales</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">manager_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employeenumber</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dob</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_manager</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing ap via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.ap"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.ar"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.batch"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.employee-to-ec"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.warehouse-inventory"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.entity-note"
               xreflabel="public.entity_note">
        <title id="public.table.entity-note-title">
         Table:
         <database class="view">entity_note</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity_note</title>

          <varlistentry>
            <term>entity_note_note_class_check</term>
            <listitem><para>CHECK ((note_class = 1))</para></listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on entity_note</title>

          <varlistentry>
            <term>entity_note_id_idx</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>entity_note_vectors_idx</term>
            <listitem><para>vector</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.entity-other-name"
               xreflabel="public.entity_other_name">
        <title id="public.table.entity-other-name-title">
         Table:
         <database class="view">entity_other_name</database>
         
        </title>
 

        <para>
           Similar to company_other_name, a person
may be jd, Joshua Drake, linuxpoet... all are the same person.  Currently
unused in the front-end but will likely be added in future versions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_other_name</database>
            </title>


            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">other_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity_other_name</title>

          <varlistentry>
            <term>entity_other_name_other_name_check</term>
            <listitem><para>CHECK ((other_name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.entity-to-contact"
               xreflabel="public.entity_to_contact">
        <title id="public.table.entity-to-contact-title">
         Table:
         <database class="view">entity_to_contact</database>
         
        </title>
 

        <para>
           This table stores contact information for entities
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_to_contact</database>
            </title>


            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contact_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.contact-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">contact</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on entity_to_contact</title>

          <varlistentry>
            <term>entity_to_contact_contact_check</term>
            <listitem><para>CHECK ((contact ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.entity-to-location"
               xreflabel="public.entity_to_location">
        <title id="public.table.entity-to-location-title">
         Table:
         <database class="view">entity_to_location</database>
         
        </title>
 

        <para>
           This table is used for locations generic to companies.  For contract-bound
addresses, use eca_to_location instead 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">entity_to_location</database>
            </title>


            <varlistentry>
              <term><database class="field">location_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.location"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">location_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.location-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.exchangerate"
               xreflabel="public.exchangerate">
        <title id="public.table.exchangerate-title">
         Table:
         <database class="view">exchangerate</database>
         
        </title>
 

        <para>
           When you receive money in a foreign currency, it is worth to you in your local currency
whatever you can get for it when you sell the acquired currency (sell rate).
When you have to pay someone in a foreign currency, the equivalent amount is the amount
you have to spend to acquire the foreign currency (buy rate).
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">exchangerate</database>
            </title>


            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">buy</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sell</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on exchangerate</title>

          <varlistentry>
            <term>exchangerate_ct_key</term>
            <listitem><para>curr, transdate</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.file-base"
               xreflabel="public.file_base">
        <title id="public.table.file-base-title">
         Table:
         <database class="view">file_base</database>
         
        </title>
 

        <para>
          Abstract table, holds no records.  Inheriting table store actual file
attachment data. Can be queried however to retrieve lists of all files. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_base</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.mime-type"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para>This column inheriting tables is used to reference the database row for the
attachment.  Inheriting tables MUST set the foreign key here appropriately.

This can also be used to create classifications of other documents, such as by
source of automatic import (where the file is not yet attached) or
even standard,
long-lived documents.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-class"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-class"
               xreflabel="public.file_class">
        <title id="public.table.file-class-title">
         Table:
         <database class="view">file_class</database>
         
        </title>
 

        <para>
           File classes are collections of files attached against rows in specific
tables in the database.  They can be used in the future to implement other form
of file attachment. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing file_base via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.file-base"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-secondary-attachment"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-view-catalog"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.file-eca"
               xreflabel="public.file_eca">
        <title id="public.table.file-eca-title">
         Table:
         <database class="view">file_eca</database>
         
        </title>
 

        <para>
           File attachments primarily attached to customer and vendor agreements.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_eca</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_eca</title>

          <varlistentry>
            <term>file_eca_file_class_check</term>
            <listitem><para>CHECK ((file_class = 5))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-entity"
               xreflabel="public.file_entity">
        <title id="public.table.file-entity-title">
         Table:
         <database class="view">file_entity</database>
         
        </title>
 

        <para>
           File attachments primarily attached to entities.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_entity</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_entity</title>

          <varlistentry>
            <term>file_entity_file_class_check</term>
            <listitem><para>CHECK ((file_class = 4))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-incoming"
               xreflabel="public.file_incoming">
        <title id="public.table.file-incoming-title">
         Table:
         <database class="view">file_incoming</database>
         
        </title>
 

        <para>
           This is essentially a spool for files to be reviewed and attached.  It is
important that the names are somehow guaranteed to be unique, so one may want to prepend them with an email equivalent or the like.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_incoming</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> Always must be 0, and we have no primary key since these files all
are for interal incoming use, not categorized.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_incoming</title>

          <varlistentry>
            <term>file_incoming_file_class_check</term>
            <listitem><para>CHECK ((file_class = 7))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>file_incoming_ref_key_check</term>
            <listitem><para>CHECK ((ref_key = 0))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-internal"
               xreflabel="public.file_internal">
        <title id="public.table.file-internal-title">
         Table:
         <database class="view">file_internal</database>
         
        </title>
 

        <para>
           This is for internal files used operationally by LedgerSMB.  For example,
company logos would be here.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_internal</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> Always must be 0, and we have no primary key since these files all
are for internal use and against the company, not categorized.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_internal</title>

          <varlistentry>
            <term>file_internal_file_class_check</term>
            <listitem><para>CHECK ((file_class = 6))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>file_internal_ref_key_check</term>
            <listitem><para>CHECK ((ref_key = 0))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.file-links"
               xreflabel="public.file_links">
        <title id="public.view.file-links-title">
         View:
         <database class="table">file_links</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_links</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">type</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_ref</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view file_links</title>
         <programlisting>
SELECT file_tx_links.file_id
,
    file_tx_links.ref_key
,
    file_tx_links.reference
,
    file_tx_links.type
,
    file_tx_links.dest_class
,
    file_tx_links.source_class
,
    file_tx_links.dest_ref
   
FROM file_tx_links

UNION
 
SELECT file_order_links.file_id
,
    file_order_links.ref_key
,
    file_order_links.reference
,
    file_order_links.oe_class AS type
,
    file_order_links.dest_class
,
    file_order_links.source_class
,
    file_order_links.dest_ref
   
FROM file_order_links;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.file-order"
               xreflabel="public.file_order">
        <title id="public.table.file-order-title">
         Table:
         <database class="view">file_order</database>
         
        </title>
 

        <para>
           File attachments primarily attached to orders and quotations.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_order</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.oe"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_order</title>

          <varlistentry>
            <term>file_order_file_class_check</term>
            <listitem><para>CHECK ((file_class = 2))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing file_order_to_order via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.file-order-to-order"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-order-to-tx"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.file-order-links"
               xreflabel="public.file_order_links">
        <title id="public.view.file-order-links-title">
         View:
         <database class="table">file_order_links</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_order_links</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">oe_class</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_ref</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view file_order_links</title>
         <programlisting>
SELECT sl.file_id
,
    sl.ref_key
,
    oe.ordnumber AS reference
,
    oc.oe_class
,
    sl.dest_class
,
    sl.source_class
,
    sl.ref_key AS dest_ref
   
FROM (
     (file_secondary_attachment sl
     
        JOIN oe 
          ON (
                 (sl.ref_key = oe.id)
           )
     )
     
  JOIN oe_class oc 
    ON (
           (oe.oe_class_id = oc.id)
     )
)
  
WHERE (sl.source_class = 2);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.file-order-to-order"
               xreflabel="public.file_order_to_order">
        <title id="public.table.file-order-to-order-title">
         Table:
         <database class="view">file_order_to_order</database>
         
        </title>
 

        <para>
           Secondary links from one order to another, for example to support order
consolidation.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_order_to_order</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-order"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.oe"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_order_to_order</title>

          <varlistentry>
            <term>file_order_to_order_dest_class_check</term>
            <listitem><para>CHECK ((dest_class = 2))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>file_order_to_order_source_class_check</term>
            <listitem><para>CHECK ((source_class = 2))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-order-to-tx"
               xreflabel="public.file_order_to_tx">
        <title id="public.table.file-order-to-tx-title">
         Table:
         <database class="view">file_order_to_tx</database>
         
        </title>
 

        <para>
           Secondary links from orders to transactions, for example to track files when
invoices are generated from orders.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_order_to_tx</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-order"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.gl"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_order_to_tx</title>

          <varlistentry>
            <term>file_order_to_tx_dest_class_check</term>
            <listitem><para>CHECK ((dest_class = 1))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>file_order_to_tx_source_class_check</term>
            <listitem><para>CHECK ((source_class = 2))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-part"
               xreflabel="public.file_part">
        <title id="public.table.file-part-title">
         Table:
         <database class="view">file_part</database>
         
        </title>
 

        <para>
           File attachments primarily attached to goods and services.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_part</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_part</title>

          <varlistentry>
            <term>file_part_file_class_check</term>
            <listitem><para>CHECK ((file_class = 3))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-secondary-attachment"
               xreflabel="public.file_secondary_attachment">
        <title id="public.table.file-secondary-attachment-title">
         Table:
         <database class="view">file_secondary_attachment</database>
         
        </title>
 

        <para>
          Another abstract table.  This one will use rewrite rules to make inserts safe
because of the difficulty in managing inserts otherwise. Inheriting tables
provide secondary links between the file and other database objects.

Due to the nature of database inheritance and unique constraints
in PostgreSQL, this must be partitioned in a star format.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_secondary_attachment</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.file-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-transaction"
               xreflabel="public.file_transaction">
        <title id="public.table.file-transaction-title">
         Table:
         <database class="view">file_transaction</database>
         
        </title>
 

        <para>
           File attachments primarily attached to AR/AP/GL.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_transaction</database>
            </title>


            <varlistentry>
              <term><database class="field">content</database></term>
              <listitem><para>
                <database class="datatype">bytea</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">uploaded_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT nextval(&apos;file_base_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_transaction</title>

          <varlistentry>
            <term>file_transaction_file_class_check</term>
            <listitem><para>CHECK ((file_class = 1))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing file_tx_to_order via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.file-tx-to-order"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.file-tx-links"
               xreflabel="public.file_tx_links">
        <title id="public.view.file-tx-links-title">
         View:
         <database class="table">file_tx_links</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_tx_links</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">type</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_ref</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view file_tx_links</title>
         <programlisting>
SELECT sl.file_id
,
    sl.ref_key
,
    gl.reference
,
    gl.type
,
    sl.dest_class
,
    sl.source_class
,
    sl.ref_key AS dest_ref
   
FROM (file_secondary_attachment sl
     
  JOIN (
      SELECT gl_1.id
           ,
            gl_1.reference
           ,
            &apos;gl&apos;::text AS type
           
        FROM gl gl_1
        
       UNION
         
      SELECT ar.id
           ,
            ar.invnumber
           ,
                CASE
                    WHEN ar.invoice THEN &apos;is&apos;::text
                    ELSE &apos;ar&apos;::text
                END AS type
           
        FROM ar
        
       UNION
         
      SELECT ap.id
           ,
            ap.invnumber
           ,
                CASE
                    WHEN ap.invoice THEN &apos;ir&apos;::text
                    ELSE &apos;ap&apos;::text
                END AS type
           
        FROM ap
     ) gl 
    ON (
           (
                 (sl.ref_key = gl.id)
               AND (sl.source_class = 1)
           )
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.file-tx-to-order"
               xreflabel="public.file_tx_to_order">
        <title id="public.table.file-tx-to-order-title">
         Table:
         <database class="view">file_tx_to_order</database>
         
        </title>
 

        <para>
           Secondary links from journal entries to orders.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_tx_to_order</database>
            </title>


            <varlistentry>
              <term><database class="field">file_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-transaction"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.oe"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dest_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attached_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on file_tx_to_order</title>

          <varlistentry>
            <term>file_tx_to_order_dest_class_check</term>
            <listitem><para>CHECK ((dest_class = 2))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>file_tx_to_order_source_class_check</term>
            <listitem><para>CHECK ((source_class = 1))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.file-view-catalog"
               xreflabel="public.file_view_catalog">
        <title id="public.table.file-view-catalog-title">
         Table:
         <database class="view">file_view_catalog</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">file_view_catalog</database>
            </title>


            <varlistentry>
              <term><database class="field">file_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.file-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">view_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.fixes"
               xreflabel="public.fixes">
        <title id="public.table.fixes-title">
         Table:
         <database class="view">fixes</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">fixes</database>
            </title>


            <varlistentry>
              <term><database class="field">checksum</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">path</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">stdout</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">stderr</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">applied_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.gifi"
               xreflabel="public.gifi">
        <title id="public.table.gifi-title">
         Table:
         <database class="view">gifi</database>
         
        </title>
 

        <para>
           GIFI labels for accounts, used in Canada and some EU countries for tax
reporting
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">gifi</database>
            </title>


            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.gl"
               xreflabel="public.gl">
        <title id="public.table.gl-title">
         Table:
         <database class="view">gl</database>
         
        </title>
 

        <para>
           This table holds summary information for entries in the general journal.
Does not hold summary information in 1.3 for AR or AP entries.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">gl</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;id&apos;::regclass)</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

              <para> the person_id of the employee who created
the entry.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_report via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-report"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-order-to-tx"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.yearend"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.inventory-report"
               xreflabel="public.inventory_report">
        <title id="public.table.inventory-report-title">
         Table:
         <database class="view">inventory_report</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">inventory_report</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">source</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ar_trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ap_trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing inventory_report_line via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.inventory-report-line"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.inventory-report-line"
               xreflabel="public.inventory_report_line">
        <title id="public.table.inventory-report-line-title">
         Table:
         <database class="view">inventory_report_line</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">inventory_report_line</database>
            </title>


            <varlistentry>
              <term><database class="field">adjust_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.inventory-report"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">counted</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">expected</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">variance</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.invoice"
               xreflabel="public.invoice">
        <title id="public.table.invoice-title">
         Table:
         <database class="view">invoice</database>
         
        </title>
 

        <para>
          Line items of invoices with goods/services attached.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">invoice</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para>Positive is normal for sales invoices, negative for vendor invoices.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">allocated</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para>Number of allocated items, negative relative to qty.
When qty + allocated = 0, then the item is fully used for purposes of COGS
calculations.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">precision</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">fxsellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">assemblyitem</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">deliverydate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">serialnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vendor_sku</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on invoice</title>

          <varlistentry>
            <term>invoice_allocation_constraint</term>
            <listitem><para>CHECK ((((allocated * (&apos;-1&apos;::integer)::numeric) &gt;= LEAST((0)::numeric, qty)) AND ((allocated * (&apos;-1&apos;::integer)::numeric) &lt;= GREATEST(qty, (0)::numeric))))</para></listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on invoice</title>

          <varlistentry>
            <term>invoice_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>invoice_trans_id_key</term>
            <listitem><para>trans_id</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing acc_trans via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.acc-trans"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.business-unit-inv"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.invoice-note"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.invoice-tax-form"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.invoice-note"
               xreflabel="public.invoice_note">
        <title id="public.table.invoice-note-title">
         Table:
         <database class="view">invoice_note</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">invoice_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.invoice"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on invoice_note</title>

          <varlistentry>
            <term>invoice_note_id_idx</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>invoice_note_vectors_idx</term>
            <listitem><para>vector</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.view.invoice-sum"
               xreflabel="public.invoice_sum">
        <title id="public.view.invoice-sum-title">
         View:
         <database class="table">invoice_sum</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">invoice_sum</database>
            </title>


            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view invoice_sum</title>
         <programlisting>
SELECT a.transdate
,
    sum
(i.qty) AS qty
,
    i.parts_id
   
FROM (invoice i
     
  JOIN (
      SELECT ar.id
           ,
            ar.transdate
           
        FROM ar
          
       WHERE ar.approved
        
       UNION
         
      SELECT ap.id
           ,
            ap.transdate
           
        FROM ap
          
       WHERE ap.approved
     ) a 
    ON (
           (i.trans_id = a.id)
     )
)
  
GROUP BY a.transdate
, i.parts_id;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.invoice-tax-form"
               xreflabel="public.invoice_tax_form">
        <title id="public.table.invoice-tax-form-title">
         Table:
         <database class="view">invoice_tax_form</database>
         
        </title>
 

        <para>
           Maping invoice to country_tax_form.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">invoice_tax_form</database>
            </title>


            <varlistentry>
              <term><database class="field">invoice_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.invoice"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reportable</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.jcitems"
               xreflabel="public.jcitems">
        <title id="public.table.jcitems-title">
         Table:
         <database class="view">jcitems</database>
         
        </title>
 

        <para>
           Time and materials cards.
Materials cards not implemented.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">jcitems</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">business_unit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">allocated</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">fxsellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">serialnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">checkedin</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">checkedout</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">total</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">non_billable</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">jctype</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on jcitems</title>

          <varlistentry>
            <term>jcitems_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.jctype"
               xreflabel="public.jctype">
        <title id="public.table.jctype-title">
         Table:
         <database class="view">jctype</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">jctype</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_service</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_timecard</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.job"
               xreflabel="public.job">
        <title id="public.table.job-title">
         Table:
         <database class="view">job</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">job</database>
            </title>


            <varlistentry>
              <term><database class="field">bu_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.business-unit"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

              <para> Job costing/manufacturing here not implemented.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">production</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">completed</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.journal-entry"
               xreflabel="public.journal_entry">
        <title id="public.table.journal-entry-title">
         Table:
         <database class="view">journal_entry</database>
         
        </title>
 

        <para>
          
This tale records the header information for each transaction.  It replaces
parts of the following tables:  acc_trans, ar, ap, gl, transactions.

Note now all ar/ap transactions are also journal entries.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">journal_entry</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para> Invoice number or journal entry number.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">locked_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.session"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">journal</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.journal-type"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">post_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">effective_start</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

              <para> For transactions whose effects are spread out over a period of time, this is
the effective start date for the transaction.  To be used by add-ons for
automating adjustments.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">effective_end</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

              <para> For transactions whose effects are spread out over a period of time, this is
the effective end date for the transaction.  To be used by add-ons for
automating adjustments.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">currency</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">is_template</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> Set true for template transactions.  Templates can never be approved but can
be copied into new transactions and are useful for recurrances. </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entered_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on journal_entry</title>

          <varlistentry>
            <term>journal_entry_check</term>
            <listitem><para>CHECK (((is_template IS FALSE) OR (approved IS FALSE)))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>journal_entry_check1</term>
            <listitem><para>CHECK ((is_template OR (reference IS NOT NULL)))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing eca_invoice via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.eca-invoice"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-note"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.journal-line"
               xreflabel="public.journal_line">
        <title id="public.table.journal-line-title">
         Table:
         <database class="view">journal_line</database>
         
        </title>
 

        <para>
           Replaces acc_trans as the main account transaction line table.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">journal_line</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">journal_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.journal-entry"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cleared</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

              <para> Still needed both for legacy data and in case reconciliation data must
eventually be purged.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reconciliation_report</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.cr-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">line_type</database></term>
              <listitem><para>
                <database class="datatype">text</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account-link-description"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on journal_line</title>

          <varlistentry>
            <term>journal_line_amount_check</term>
            <listitem><para>CHECK ((amount &lt;&gt; &apos;NaN&apos;::numeric))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing business_unit_jl via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.business-unit-jl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment-map"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.journal-note"
               xreflabel="public.journal_note">
        <title id="public.table.journal-note-title">
         Table:
         <database class="view">journal_note</database>
         
        </title>
 

        <para>
           This stores notes attached to journal entries, including payments and
invoices.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">journal_note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT nextval(&apos;note_id_seq&apos;::regclass)</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.journal-entry"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">internal_only</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT false</literal>



              </para>

              <para> When set to true, does not show up in notes list for invoice templates</para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on journal_note</title>

          <varlistentry>
            <term>journal_note_note_class_check</term>
            <listitem><para>CHECK ((note_class = 5))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.journal-type"
               xreflabel="public.journal_type">
        <title id="public.table.journal-type-title">
         Table:
         <database class="view">journal_type</database>
         
        </title>
 

        <para>
           This table describes the journal entry type of the transaction.  The
following values are hard coded by default:
1:  General journal
2:  Sales (AR)
3:  Purchases (AP)
4:  Receipts
5:  Payments


        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">journal_type</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing journal_entry via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.journal-entry"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.language"
               xreflabel="public.language">
        <title id="public.table.language-title">
         Table:
         <database class="view">language</database>
         
        </title>
 

        <para>
           Languages for manual translations and so forth.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">language</database>
            </title>


            <varlistentry>
              <term><database class="field">code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing eca_invoice via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.eca-invoice"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.template"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.user-preference"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.location"
               xreflabel="public.location">
        <title id="public.table.location-title">
         Table:
         <database class="view">location</database>
         
        </title>
 

        <para>
          
This table stores addresses, such as shipto and bill to addresses.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">location</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">line_one</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">line_two</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">line_three</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">city</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">state</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.country"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mail_code</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">inactive_date</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">active</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on location</title>

          <varlistentry>
            <term>location_city_check</term>
            <listitem><para>CHECK ((city ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>location_line_one_check</term>
            <listitem><para>CHECK ((line_one ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>location_mail_code_check</term>
            <listitem><para>CHECK ((mail_code ~ &apos;[[:alnum:]_-]&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>location_state_check</term>
            <listitem><para>CHECK ((state ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing eca_to_location via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.eca-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.new-shipto"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.person-to-company"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.location-class"
               xreflabel="public.location_class">
        <title id="public.table.location-class-title">
         Table:
         <database class="view">location_class</database>
         
        </title>
 

        <para>
          
Individuals seeking to add new location classes should coordinate with others.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">location_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">authoritative</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on location_class</title>

          <varlistentry>
            <term>location_class_class_check</term>
            <listitem><para>CHECK ((class ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing eca_to_location via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.eca-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-to-location"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.location-class-to-entity-class"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.location-class-to-entity-class"
               xreflabel="public.location_class_to_entity_class">
        <title id="public.table.location-class-to-entity-class-title">
         Table:
         <database class="view">location_class_to_entity_class</database>
         
        </title>
 

        <para>
          This determines which location classes go with which entity classes
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">location_class_to_entity_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">location_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.location-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-class"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.lsmb-group"
               xreflabel="public.lsmb_group">
        <title id="public.table.lsmb-group-title">
         Table:
         <database class="view">lsmb_group</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">lsmb_group</database>
            </title>


            <varlistentry>
              <term><database class="field">role_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing lsmb_group_grants via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.lsmb-group-grants"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.lsmb-group-grants"
               xreflabel="public.lsmb_group_grants">
        <title id="public.table.lsmb-group-grants-title">
         Table:
         <database class="view">lsmb_group_grants</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">lsmb_group_grants</database>
            </title>


            <varlistentry>
              <term><database class="field">group_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.lsmb-group"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">granted_role</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.lsmb-module"
               xreflabel="public.lsmb_module">
        <title id="public.table.lsmb-module-title">
         Table:
         <database class="view">lsmb_module</database>
         
        </title>
 

        <para>
           This stores categories functionality into modules.  Addons may add rows here, but
the id should be hardcoded.  As always 900-1000 will be reserved for internal use,
and negative numbers will be reserved for testing.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">lsmb_module</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing bu_class_to_module via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.bu-class-to-module"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.lsmb-sequence"
               xreflabel="public.lsmb_sequence">
        <title id="public.table.lsmb-sequence-title">
         Table:
         <database class="view">lsmb_sequence</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">lsmb_sequence</database>
            </title>


            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">setting_key</database></term>
              <listitem><para>
                <database class="datatype">text</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.defaults"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">prefix</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">suffix</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sequence</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;1&apos;::text</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accept_input</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT true</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.makemodel"
               xreflabel="public.makemodel">
        <title id="public.table.makemodel-title">
         Table:
         <database class="view">makemodel</database>
         
        </title>
 

        <para>
           A single parts entry can have multiple make/model entries.  These
store manufacturer/model number info.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">makemodel</database>
            </title>


            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">barcode</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">make</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">model</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on makemodel</title>

          <varlistentry>
            <term>makemodel_make_key</term>
            <listitem><para>lower(make)</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>makemodel_model_key</term>
            <listitem><para>lower(model)</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>makemodel_parts_id_key</term>
            <listitem><para>parts_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.menu-acl"
               xreflabel="public.menu_acl">
        <title id="public.table.menu-acl-title">
         Table:
         <database class="view">menu_acl</database>
         
        </title>
 

        <para>
          Provides access control list entries for menu nodes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">menu_acl</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">role_name</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">acl_type</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>







              </para>

              <para> Nodes are hidden unless a role is found of which the user is a member, and
where the acl_type for that role type and node is set to &apos;allow&apos; and no acl is
found for any role of which the user is a member, where the acl_type is set to
&apos;deny&apos;.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">node_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.menu-node"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on menu_acl</title>

          <varlistentry>
            <term>menu_acl_acl_type_check</term>
            <listitem><para>CHECK ((((acl_type)::text = &apos;allow&apos;::text) OR ((acl_type)::text = &apos;deny&apos;::text)))</para></listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on menu_acl</title>

          <varlistentry>
            <term>menu_acl_node_id_idx</term>
            <listitem><para>node_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.menu-attribute"
               xreflabel="public.menu_attribute">
        <title id="public.table.menu-attribute-title">
         Table:
         <database class="view">menu_attribute</database>
         
        </title>
 

        <para>
           This table stores the callback information for each menu item.  The
attributes are stored in key/value modelling because of the fact that this
best matches the semantic structure of the information.

Each node should have EITHER a menu or a module attribute, menu for a menu with
sub-items, module for an executiable script.  The module attribute identifies
the perl script to be run.  The action attribute identifies the entry point.

Beyond this, any other attributes that should be passed in can be done as other
attributes.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">menu_attribute</database>
            </title>


            <varlistentry>
              <term><database class="field">node_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.menu-node"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">attribute</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">value</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.menu-friendly"
               xreflabel="public.menu_friendly">
        <title id="public.view.menu-friendly-title">
         View:
         <database class="table">menu_friendly</database>
         
        </title>
 

        <para>
           A nice human-readable view for investigating the menu tree.  Does not
show menu attributes or acls.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">menu_friendly</database>
            </title>


            <varlistentry>
              <term><database class="field">level</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">path</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">position</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view menu_friendly</title>
         <programlisting> WITH RECURSIVE tree
(path
     , id
     , parent
     , level
     , positions
) AS 
(
         
SELECT (menu_node.id)::text AS path
     ,
            menu_node.id
     ,
            menu_node.parent
     ,
            0 AS level
     ,
            
     (menu_node.&quot;position&quot;)::text AS &quot;position&quot;
           
  FROM menu_node
          
 WHERE (menu_node.parent IS NULL)
        
 UNION
         
SELECT (
           (t_1.path || 
               &apos;,&apos;::text
           ) || 
           (n_1.id)::text
     )
     ,
            n_1.id
     ,
            n_1.parent
     ,
            
     (t_1.level + 1)
     ,
            
     (
           (t_1.positions || 
               &apos;,&apos;::text
           ) || n_1.&quot;position&quot;
     )
           
  FROM (menu_node n_1
             
        JOIN tree t_1 
          ON (
                 (t_1.id = n_1.parent)
           )
     )
        
)
 
SELECT t.level
,
    t.path
,
    
(repeat
     (&apos; &apos;::text
           , (2 * t.level)
     ) || 
     (n.label)::text
) AS label
,
    n.id
,
    n.&quot;position&quot;
   
FROM (tree t
     
  JOIN menu_node n 
 USING (id)
)
  
ORDER BY (string_to_array
     (t.positions
           ,&apos;,&apos;::text
     )
)::integer[];</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.menu-node"
               xreflabel="public.menu_node">
        <title id="public.table.menu-node-title">
         Table:
         <database class="view">menu_node</database>
         
        </title>
 

        <para>
          This table stores the tree structure of the menu.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">menu_node</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">character varying</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parent</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE#1</database>









                <database class="constraint">REFERENCES <xref linkend="public.table.menu-node"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">position</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing menu_acl via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.menu-acl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.menu-attribute"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.menu-node"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.mfg-lot"
               xreflabel="public.mfg_lot">
        <title id="public.table.mfg-lot-title">
         Table:
         <database class="view">mfg_lot</database>
         
        </title>
 

        <para>
           This tracks assembly restocks.  This is designed to work with old code and
may change as we refactor the parts.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">mfg_lot</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">lot_number</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (nextval(&apos;lot_tracking_number&apos;::regclass))::text</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">stock_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (now())::date</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing mfg_lot_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.mfg-lot-item"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.mfg-lot-item"
               xreflabel="public.mfg_lot_item">
        <title id="public.table.mfg-lot-item-title">
         Table:
         <database class="view">mfg_lot_item</database>
         
        </title>
 

        <para>
           This tracks items used in assembly restocking.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">mfg_lot_item</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mfg_lot_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.mfg-lot"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.mime-type"
               xreflabel="public.mime_type">
        <title id="public.table.mime-type-title">
         Table:
         <database class="view">mime_type</database>
         
        </title>
 

        <para>
           This is a lookup table for storing MIME types.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">mime_type</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">mime_type</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">invoice_include</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing file_base via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.file-base"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.new-shipto"
               xreflabel="public.new_shipto">
        <title id="public.table.new-shipto-title">
         Table:
         <database class="view">new_shipto</database>
         
        </title>
 

        <para>
           Tracks ship_to information for orders and invoices.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">new_shipto</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">oe_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.oe"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">location_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.location"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.note"
               xreflabel="public.note">
        <title id="public.table.note-title">
         Table:
         <database class="view">note</database>
         
        </title>
 

        <para>
           This is an abstract table which should have zero rows.  It is inherited by
other tables for specific notes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">note</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.note-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">note</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

              <para>Body of note.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">vector</database></term>
              <listitem><para>
                <database class="datatype">tsvector</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;&apos;::tsvector</literal>



              </para>

              <para>tsvector for full text indexing, requires
both setting up tsearch dictionaries and adding triggers to use at present.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">text</database>





                <literal>DEFAULT &quot;session_user&quot;()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ref_key</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

              <para> Subclassed tables use this column as a foreign key against the table storing
the record a note is attached to.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">subject</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.note-class"
               xreflabel="public.note_class">
        <title id="public.table.note-class-title">
         Table:
         <database class="view">note_class</database>
         
        </title>
 

        <para>
           Coordinate with others before adding entries. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">note_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">class</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on note_class</title>

          <varlistentry>
            <term>note_class_class_check</term>
            <listitem><para>CHECK ((class ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing note via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.note"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.oe"
               xreflabel="public.oe">
        <title id="public.table.oe-title">
         Table:
         <database class="view">oe</database>
         
        </title>
 

        <para>
           Header information for:
* Sales orders
* Purchase Orders
* Quotations
* Requests for Quotation

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">oe</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ordnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">netamount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reqdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxincluded</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shippingpoint</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">quotation</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">quonumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">intnotes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shipvia</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ponumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">terms</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_account</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">oe_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.oe-class"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on oe</title>

          <varlistentry>
            <term>oe_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>oe_ordnumber_key</term>
            <listitem><para>ordnumber</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>oe_transdate_key</term>
            <listitem><para>transdate</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing file_order via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.file-order"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-order-to-order"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-tx-to-order"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.new-shipto"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.oe-class"
               xreflabel="public.oe_class">
        <title id="public.table.oe-class-title">
         Table:
         <database class="view">oe_class</database>
         
        </title>
 

        <para>
           Hardwired classifications for orders and quotations.
Coordinate before adding.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">oe_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>




                <database class="constraint">UNIQUE</database>










              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">oe_class</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on oe_class</title>

          <varlistentry>
            <term>oe_class_id_check</term>
            <listitem><para>CHECK ((id = ANY (ARRAY[1, 2, 3, 4])))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing oe via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.oe"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.open-forms"
               xreflabel="public.open_forms">
        <title id="public.table.open-forms-title">
         Table:
         <database class="view">open_forms</database>
         
        </title>
 

        <para>
           This is our primary anti-xsrf measure, as this allows us to require a full
round trip to the web server in order to save data.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">open_forms</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">session_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.session"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">form_name</database></term>
              <listitem><para>
                <database class="datatype">character varying(100)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_used</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.order-sum"
               xreflabel="public.order_sum">
        <title id="public.view.order-sum-title">
         View:
         <database class="table">order_sum</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">order_sum</database>
            </title>


            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view order_sum</title>
         <programlisting>
SELECT oe.transdate
,
    sum
(
     (oi.ship * 
           (
        CASE
            WHEN 
                 (oe.oe_class_id = 1) THEN 1
            ELSE &apos;-1&apos;::integer
        END
           )::numeric
     )
) AS qty
,
    oi.parts_id
   
FROM (orderitems oi
     
  JOIN oe 
    ON (
           (
                 (oe.closed IS FALSE)
               AND (oe.oe_class_id = ANY 
                       (ARRAY[1
                             , 2]
                       )
                 )
           )
     )
)
  
GROUP BY oe.transdate
, oi.parts_id;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.orderitems"
               xreflabel="public.orderitems">
        <title id="public.table.orderitems-title">
         Table:
         <database class="view">orderitems</database>
         
        </title>
 

        <para>
           Line items for sales/purchase orders and quotations.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">orderitems</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">precision</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit</database></term>
              <listitem><para>
                <database class="datatype">character varying(5)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reqdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ship</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">serialnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on orderitems</title>

          <varlistentry>
            <term>orderitems_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>orderitems_trans_id_key</term>
            <listitem><para>trans_id</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing business_unit_oitem via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.business-unit-oitem"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.overpayments"
               xreflabel="public.overpayments">
        <title id="public.view.overpayments-title">
         View:
         <database class="table">overpayments</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">overpayments</database>
            </title>


            <varlistentry>
              <term><database class="field">payment_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">accno</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">available</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">legal_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">discount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">meta_number</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view overpayments</title>
         <programlisting>
SELECT p.id AS payment_id
,
    p.reference AS payment_reference
,
    p.payment_class
,
    p.closed AS payment_closed
,
    p.payment_date
,
    ac.chart_id
,
    c.accno
,
    c.description AS chart_description
,
    
(sum
     (ac.amount) * 
     (
        CASE
            WHEN 
           (eca.entity_class = 1) THEN &apos;-1&apos;::integer
            ELSE 1
        END
     )::numeric
) AS available
,
    cmp.legal_name
,
    eca.id AS entity_credit_id
,
    eca.entity_id
,
    eca.discount
,
    eca.meta_number
   
FROM (
     (
           (
                 (
                       (payment p
     
                          JOIN payment_links pl 
                            ON (
                                   (pl.payment_id = p.id)
                             )
                       )
     
                    JOIN acc_trans ac 
                      ON (
                             (ac.entry_id = pl.entry_id)
                       )
                 )
     
              JOIN chart c 
                ON (
                       (c.id = ac.chart_id)
                 )
           )
     
        JOIN entity_credit_account eca 
          ON (
                 (eca.id = p.entity_credit_id)
           )
     )
     
  JOIN company cmp 
    ON (
           (cmp.entity_id = eca.entity_id)
     )
)
  
WHERE (
     (p.gl_id IS NOT NULL)
   AND (
           (pl.type = 2)
          OR (pl.type = 0)
     )
   AND (c.link ~~ &apos;%overpayment%&apos;::text)
)
  
GROUP BY p.id
, c.accno
, p.reference
, p.payment_class
, p.closed
, p.payment_date
, ac.chart_id
, c.description
, cmp.legal_name
, eca.id
, eca.entity_id
, eca.discount
, eca.meta_number
, eca.entity_class;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.parts"
               xreflabel="public.parts">
        <title id="public.table.parts-title">
         Table:
         <database class="view">parts</database>
         
        </title>
 

        <para>
          This stores detail information about goods and services.  The type of part
is currently defined according to the following rules:
* If assembly is true, then an assembly
* If inventory_accno_id, income_accno_id, and expense_accno_id are not null then
  a part.
* If inventory_accno_id is null but the other two are not, then a service.
* Otherwise, a labor/overhead entry.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">parts</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">partnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit</database></term>
              <listitem><para>
                <database class="datatype">character varying(5)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">listprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">lastcost</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">priceupdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">weight</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">onhand</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">makemodel</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">assembly</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">alternate</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rop</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

              <para>Re-order point.  Used to select parts for short inventory report.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">inventory_accno_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">income_accno_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">expense_accno_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">returns_accno_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bin</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Text identifier for where a part is stored.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">obsolete</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">bom</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para>Show on Bill of Materials.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">image</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

              <para>Hyperlink to product image.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">drawing</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">microfiche</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">partsgroup_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">avgcost</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on parts</title>

          <varlistentry>
            <term>parts_description_key</term>
            <listitem><para>lower(description)</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>parts_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>parts_partnumber_key</term>
            <listitem><para>lower(partnumber)</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing assembly via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.assembly"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-part"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.inventory-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.invoice"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.makemodel"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.mfg-lot"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.mfg-lot-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.orderitems"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.parts-translation"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partscustomer"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partstax"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.parts-translation"
               xreflabel="public.parts_translation">
        <title id="public.table.parts-translation-title">
         Table:
         <database class="view">parts_translation</database>
         
        </title>
 

        <para>
           Translation information for parts.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">parts_translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.partscustomer"
               xreflabel="public.partscustomer">
        <title id="public.table.partscustomer-title">
         Table:
         <database class="view">partscustomer</database>
         
        </title>
 

        <para>
           Tracks per-customer pricing.  Discounts can be offered for periods of time
and for pricegroups as well as per customer
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">partscustomer</database>
            </title>


            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pricegroup_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.pricegroup"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pricebreak</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sellprice</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">validfrom</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">validto</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.partsgroup"
               xreflabel="public.partsgroup">
        <title id="public.table.partsgroup-title">
         Table:
         <database class="view">partsgroup</database>
         
        </title>
 

        <para>
           Groups of parts for Point of Sale screen.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">partsgroup</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">partsgroup</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parent</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.partsgroup"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on partsgroup</title>

          <varlistentry>
            <term>partsgroup_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing partsgroup via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.partsgroup"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partsgroup-translation"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.partsgroup-translation"
               xreflabel="public.partsgroup_translation">
        <title id="public.table.partsgroup-translation-title">
         Table:
         <database class="view">partsgroup_translation</database>
         
        </title>
 

        <para>
           Translation information for partsgroups.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">partsgroup_translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.partsgroup"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.partstax"
               xreflabel="public.partstax">
        <title id="public.table.partstax-title">
         Table:
         <database class="view">partstax</database>
         
        </title>
 

        <para>
           Mapping of parts to taxes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">partstax</database>
            </title>


            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.parts"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxcategory_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.taxcategory"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on partstax</title>

          <varlistentry>
            <term>partstax_parts_id_key</term>
            <listitem><para>parts_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.partsvendor"
               xreflabel="public.partsvendor">
        <title id="public.table.partsvendor-title">
         Table:
         <database class="view">partsvendor</database>
         
        </title>
 

        <para>
           Tracks vendor&apos;s pricing, as well as vendor&apos;s part number, lead time
required and currency.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">partsvendor</database>
            </title>


            <varlistentry>
              <term><database class="field">credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">partnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">leadtime</database></term>
              <listitem><para>
                <database class="datatype">smallint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">lastcost</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">curr</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on partsvendor</title>

          <varlistentry>
            <term>partsvendor_parts_id_key</term>
            <listitem><para>parts_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.payment"
               xreflabel="public.payment">
        <title id="public.table.payment-title">
         Table:
         <database class="view">payment</database>
         
        </title>
 

        <para>
           This table will store the main data on a payment, prepayment, overpayment, et
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payment</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

              <para> This field will store the code for both receipts and payment order  </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">gl_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.gl"/></database>


              </para>

              <para> A payment should always be linked to a GL movement </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>





                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">closed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

              <para> This will store the current state of a payment/receipt order </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-credit-account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employee_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">currency</database></term>
              <listitem><para>
                <database class="datatype">character(3)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notes</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on payment</title>

          <varlistentry>
            <term>payment_id_idx</term>
            <listitem><para>id</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing payment_links via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payment-links"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payment-links"
               xreflabel="public.payment_links">
        <title id="public.table.payment-links-title">
         Table:
         <database class="view">payment_links</database>
         
        </title>
 

        <para>
          
 An explanation to the type field.
 * A type 0 means the link is referencing an ar/ap  and was created
   using an overpayment movement after the receipt was created
 * A type 1 means the link is referencing an ar/ap and  was made
   on the payment creation, its not the product of an overpayment movement
 * A type 2 means the link is not referencing an ar/ap and its the product
   of the overpayment logic

 With this ideas in order we can do the following

 To get the payment amount we will sum the entries with type &gt; 0.
 To get the linked amount we will sum the entries with type &lt; 2.
 The overpayment account can be obtained from the entries with type = 2.

 This reasoning is hacky and i hope it can dissapear when we get to 1.4 - D.M.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payment_links</database>
            </title>


            <varlistentry>
              <term><database class="field">payment_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.payment"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">type</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payment-map"
               xreflabel="public.payment_map">
        <title id="public.table.payment-map-title">
         Table:
         <database class="view">payment_map</database>
         
        </title>
 

        <para>
           This maps the payment journal entry to the
invoices it pays.  A couple notes here:
1)  There is no requirement tht the payment &quot;invoice&quot; be linked to the same
entity_credit_account as the paid invoice.  People can pay eachothers invoices
if LedgerSMB supports this at an app level.
2)  This now means that payments are first class transactions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payment_map</database>
            </title>


            <varlistentry>
              <term><database class="field">line_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.journal-line"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pays</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.eca-invoice"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payment-type"
               xreflabel="public.payment_type">
        <title id="public.table.payment-type-title">
         Table:
         <database class="view">payment_type</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payment_type</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-deduction"
               xreflabel="public.payroll_deduction">
        <title id="public.table.payroll-deduction-title">
         Table:
         <database class="view">payroll_deduction</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_deduction</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-deduction-type"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rate</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-deduction-class"
               xreflabel="public.payroll_deduction_class">
        <title id="public.table.payroll-deduction-class-title">
         Table:
         <database class="view">payroll_deduction_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_deduction_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE#1</database>



                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.country"/></database>






              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">stored_proc_name</database></term>
              <listitem><para>
                <database class="datatype">name</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_deduction_type via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-deduction-type"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-deduction-type"
               xreflabel="public.payroll_deduction_type">
        <title id="public.table.payroll-deduction-type-title">
         Table:
         <database class="view">payroll_deduction_type</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_deduction_type</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pdc_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-deduction-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-deduction-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">default_amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">calc_percent</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_deduction via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-deduction"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-employee-class"
               xreflabel="public.payroll_employee_class">
        <title id="public.table.payroll-employee-class-title">
         Table:
         <database class="view">payroll_employee_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_employee_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_employee_class_to_income_type via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-employee-class-to-income-type"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-report"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-employee-class-to-income-type"
               xreflabel="public.payroll_employee_class_to_income_type">
        <title id="public.table.payroll-employee-class-to-income-type-title">
         Table:
         <database class="view">payroll_employee_class_to_income_type</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_employee_class_to_income_type</database>
            </title>


            <varlistentry>
              <term><database class="field">ec_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-employee-class"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">it_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-income-type"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-income-category"
               xreflabel="public.payroll_income_category">
        <title id="public.table.payroll-income-category-title">
         Table:
         <database class="view">payroll_income_category</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_income_category</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-income-class"
               xreflabel="public.payroll_income_class">
        <title id="public.table.payroll-income-class-title">
         Table:
         <database class="view">payroll_income_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_income_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE#1</database>



                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.country"/></database>






              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_income_type via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-income-type"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-income-type"
               xreflabel="public.payroll_income_type">
        <title id="public.table.payroll-income-type-title">
         Table:
         <database class="view">payroll_income_type</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_income_type</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">account_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pic_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-income-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">country_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-income-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">unit</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">default_amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_employee_class_to_income_type via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-employee-class-to-income-type"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-report-line"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-wage"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-paid-timeoff"
               xreflabel="public.payroll_paid_timeoff">
        <title id="public.table.payroll-paid-timeoff-title">
         Table:
         <database class="view">payroll_paid_timeoff</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_paid_timeoff</database>
            </title>


            <varlistentry>
              <term><database class="field">employee_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pto_class_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-pto-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">amount</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-pto-class"
               xreflabel="public.payroll_pto_class">
        <title id="public.table.payroll-pto-class-title">
         Table:
         <database class="view">payroll_pto_class</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_pto_class</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_paid_timeoff via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-paid-timeoff"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-report"
               xreflabel="public.payroll_report">
        <title id="public.table.payroll-report-title">
         Table:
         <database class="view">payroll_report</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_report</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ec_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-employee-class"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing payroll_paid_timeoff via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.payroll-paid-timeoff"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payroll-report-line"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.payroll-report-line"
               xreflabel="public.payroll_report_line">
        <title id="public.table.payroll-report-line-title">
         Table:
         <database class="view">payroll_report_line</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_report_line</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-report"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">employee_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">it_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-income-type"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rate</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.payroll-wage"
               xreflabel="public.payroll_wage">
        <title id="public.table.payroll-wage-title">
         Table:
         <database class="view">payroll_wage</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">payroll_wage</database>
            </title>


            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">type_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.payroll-income-type"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rate</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.periods"
               xreflabel="public.periods">
        <title id="public.view.periods-title">
         View:
         <database class="table">periods</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">periods</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">label</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">date_to</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">date_from</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view periods</title>
         <programlisting>
SELECT&apos;ytd&apos;::text AS id
,
    &apos;Year to Date&apos;::text AS label
,
    
(now
     ()
)::date AS date_to
,
    
(
     (
           (date_part
                 (&apos;year&apos;::text
                       , now
                       ()
                 )
           )::text || &apos;-01-01&apos;::text
     )
)::date AS date_from

UNION
 
SELECT&apos;last_year&apos;::text AS id
,
    &apos;Last Year&apos;::text AS label
,
    
(
     (
           (
                 (date_part
                       (&apos;YEAR&apos;::text
                             , now
                             ()
                       ) - 
                       (1)::double precision
                 )
           )::text || &apos;-12-31&apos;::text
     )
)::date AS date_to
,
    
(
     (
           (
                 (date_part
                       (&apos;YEAR&apos;::text
                             , now
                             ()
                       ) - 
                       (1)::double precision
                 )
           )::text || &apos;-01-01&apos;::text
     )
)::date AS date_from;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.person"
               xreflabel="public.person">
        <title id="public.table.person-title">
         Table:
         <database class="view">person</database>
         
        </title>
 

        <para>
           Every person, must have an entity to derive a common or display name. The correct way to get class information on a person would be person.entity_id-&gt;entity_class_to_entity.entity_id. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">person</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">salutation_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.salutation"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">first_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">middle_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">birthdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">personal_id</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on person</title>

          <varlistentry>
            <term>person_first_name_check</term>
            <listitem><para>CHECK ((first_name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>person_last_name_check</term>
            <listitem><para>CHECK ((last_name ~ &apos;[[:alnum:]_]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing audittrail via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.audittrail"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.gl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.jcitems"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.oe"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.payment"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.person-to-company"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.person-to-company"
               xreflabel="public.person_to_company">
        <title id="public.table.person-to-company-title">
         Table:
         <database class="view">person_to_company</database>
         
        </title>
 

        <para>
           currently unused in the front-end, but can be used to map persons
to companies.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">person_to_company</database>
            </title>


            <varlistentry>
              <term><database class="field">location_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.location"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">person_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.person"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">company_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.company"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.pricegroup"
               xreflabel="public.pricegroup">
        <title id="public.table.pricegroup-title">
         Table:
         <database class="view">pricegroup</database>
         
        </title>
 

        <para>
           Pricegroups are groups of customers who are assigned prices and discounts
together.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">pricegroup</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pricegroup</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on pricegroup</title>

          <varlistentry>
            <term>pricegroup_id_key</term>
            <listitem><para>id</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>pricegroup_pricegroup_key</term>
            <listitem><para>pricegroup</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing entity_credit_account via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.entity-credit-account"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.partscustomer"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.view.recon-payee"
               xreflabel="public.recon_payee">
        <title id="public.view.recon-payee-title">
         View:
         <database class="table">recon_payee</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">recon_payee</database>
            </title>


            <varlistentry>
              <term><database class="field">payee</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">bigint</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">report_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">scn</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">their_balance</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">our_balance</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">errorcode</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">user</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">clear_time</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">insert_time</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_type</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">post_date</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ledger_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">voucher_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">overlook</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">cleared</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view recon_payee</title>
         <programlisting>
SELECT n.name AS payee
,
    rr.id
,
    rr.report_id
,
    rr.scn
,
    rr.their_balance
,
    rr.our_balance
,
    rr.errorcode
,
    rr.&quot;user&quot;
,
    rr.clear_time
,
    rr.insert_time
,
    rr.trans_type
,
    rr.post_date
,
    rr.ledger_id
,
    ac.voucher_id
,
    rr.overlook
,
    rr.cleared
   
FROM (
     (
           (cr_report_line rr
     
         LEFT JOIN acc_trans ac 
                ON (
                       (rr.ledger_id = ac.entry_id)
                 )
           )
     
   LEFT JOIN gl 
          ON (
                 (ac.trans_id = gl.id)
           )
     )
     
LEFT JOIN (
      SELECT ap.id
           ,
            e.name
           
        FROM (
                 (ap
             
                    JOIN entity_credit_account eca 
                      ON (
                             (ap.entity_credit_account = eca.id)
                       )
                 )
             
              JOIN entity e 
                ON (
                       (eca.entity_id = e.id)
                 )
           )
        
       UNION
         
      SELECT ar.id
           ,
            e.name
           
        FROM (
                 (ar
             
                    JOIN entity_credit_account eca 
                      ON (
                             (ar.entity_credit_account = eca.id)
                       )
                 )
             
              JOIN entity e 
                ON (
                       (eca.entity_id = e.id)
                 )
           )
        
       UNION
         
      SELECT gl_1.id
           ,
            gl_1.description
           
        FROM gl gl_1
     ) n 
    ON (
           (n.id = ac.trans_id)
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.recurring"
               xreflabel="public.recurring">
        <title id="public.table.recurring-title">
         Table:
         <database class="view">recurring</database>
         
        </title>
 

        <para>
           Stores recurring information on transactions which will recur in the future.
Note that this means that only fully posted transactions can recur.
I would highly recommend depricating this table and working instead on extending
the template transaction addon to handle recurring information.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">recurring</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">startdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">nextdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">enddate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">recurring_interval</database></term>
              <listitem><para>
                <database class="datatype">interval</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">howmany</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">payment</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing recurringemail via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.recurringemail"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.recurringprint"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.recurringemail"
               xreflabel="public.recurringemail">
        <title id="public.table.recurringemail-title">
         Table:
         <database class="view">recurringemail</database>
         
        </title>
 

        <para>
          Email  to be sent out when recurring transaction is posted.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">recurringemail</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.recurring"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">formname</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">format</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">message</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.recurringprint"
               xreflabel="public.recurringprint">
        <title id="public.table.recurringprint-title">
         Table:
         <database class="view">recurringprint</database>
         
        </title>
 

        <para>
           Template, printer etc. to print to when recurring transaction posts.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">recurringprint</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.recurring"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">formname</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">format</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">printer</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.robot"
               xreflabel="public.robot">
        <title id="public.table.robot-title">
         Table:
         <database class="view">robot</database>
         
        </title>
 

        <para>
           Every robot, must have an entity to derive a common or display name. The correct way to get class information on a robot would be robot.entity_id-&gt;entity_class_to_entity.entity_id. 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">robot</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>








                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">first_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">middle_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT (&apos;now&apos;::text)::date</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on robot</title>

          <varlistentry>
            <term>robot_first_name_check</term>
            <listitem><para>CHECK ((first_name ~ &apos;[[:alnum:] _\-\.\*]?&apos;::text))</para></listitem>
          </varlistentry>



          <varlistentry>
            <term>robot_last_name_check</term>
            <listitem><para>CHECK ((last_name ~ &apos;[[:alnum:] _\-\.\*]&apos;::text))</para></listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.role-view"
               xreflabel="public.role_view">
        <title id="public.view.role-view-title">
         View:
         <database class="table">role_view</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">role_view</database>
            </title>


            <varlistentry>
              <term><database class="field">roleid</database></term>
              <listitem><para>
                <database class="datatype">oid</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">member</database></term>
              <listitem><para>
                <database class="datatype">oid</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">grantor</database></term>
              <listitem><para>
                <database class="datatype">oid</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">admin_option</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolname</database></term>
              <listitem><para>
                <database class="datatype">name</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolsuper</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolinherit</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolcreaterole</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolcreatedb</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolcanlogin</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolreplication</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolconnlimit</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolpassword</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolvaliduntil</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolbypassrls</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rolconfig</database></term>
              <listitem><para>
                <database class="datatype">text[]</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">oid</database></term>
              <listitem><para>
                <database class="datatype">oid</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view role_view</title>
         <programlisting>
SELECT m.roleid
,
    m.member
,
    m.grantor
,
    m.admin_option
,
    a.rolname
,
    a.rolsuper
,
    a.rolinherit
,
    a.rolcreaterole
,
    a.rolcreatedb
,
    a.rolcanlogin
,
    a.rolreplication
,
    a.rolconnlimit
,
    a.rolpassword
,
    a.rolvaliduntil
,
    a.rolbypassrls
,
    a.rolconfig
,
    a.oid
   
FROM (pg_auth_members m
     
  JOIN pg_roles a 
    ON (
           (m.roleid = a.oid)
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.salutation"
               xreflabel="public.salutation">
        <title id="public.table.salutation-title">
         Table:
         <database class="view">salutation</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">salutation</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">salutation</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing person via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.person"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.session"
               xreflabel="public.session">
        <title id="public.table.session-title">
         Table:
         <database class="view">session</database>
         
        </title>
 

        <para>
           This table is used to track sessions on a database level across page
requests (discretionary locks,open forms for anti-xsrf measures).
Because of the way LedgerSMB authentication works currently we do
not time out authentication when the session times out.  We do time out
highly pessimistic locks used for large batch payment workflows.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">session</database>
            </title>


            <varlistentry>
              <term><database class="field">session_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">token</database></term>
              <listitem><para>
                <database class="datatype">character varying(32)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_used</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>





                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">ttl</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT 3600</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">users_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.users"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notify_pasword</database></term>
              <listitem><para>
                <database class="datatype">interval</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;7 days&apos;::interval</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>



        <variablelist>
          <title>Constraints on session</title>

          <varlistentry>
            <term>session_token_check</term>
            <listitem><para>CHECK ((length((token)::text) = 32))</para></listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing batch via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.batch"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.journal-entry"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.open-forms"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.transactions"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.sic"
               xreflabel="public.sic">
        <title id="public.table.sic-title">
         Table:
         <database class="view">sic</database>
         
        </title>
 

        <para>
          
This can be used SIC codes or any equivalent, such as ISIC, NAICS, etc.

        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">sic</database>
            </title>


            <varlistentry>
              <term><database class="field">code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">sictype</database></term>
              <listitem><para>
                <database class="datatype">character(1)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.status"
               xreflabel="public.status">
        <title id="public.table.status-title">
         Table:
         <database class="view">status</database>
         
        </title>
 

        <para>
           Whether AR/AP transactions and invoices have been emailed and/or printed 
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">status</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">formname</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">printed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">emailed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">spoolfile</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on status</title>

          <varlistentry>
            <term>status_trans_id_key</term>
            <listitem><para>trans_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.tax"
               xreflabel="public.tax">
        <title id="public.table.tax-title">
         Table:
         <database class="view">tax</database>
         
        </title>
 

        <para>
          Information on tax rates.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">tax</database>
            </title>


            <varlistentry>
              <term><database class="field">chart_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.account"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rate</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">minvalue</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">maxvalue</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxnumber</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">validto</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>


                <database class="constraint">PRIMARY KEY</database>








                <literal>DEFAULT &apos;infinity&apos;::timestamp without time zone</literal>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">pass</database></term>
              <listitem><para>
                <database class="datatype">integer</database>



                <database class="constraint">NOT NULL</database>





              </para>

              <para>This is an integer indicating the pass of the tax. This is to support
cumultative sales tax rules (for example, Quebec charging taxes on the federal
taxes collected).</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxmodule_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT 1</literal>




                <database class="constraint">REFERENCES <xref linkend="public.table.taxmodule"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.tax-extended"
               xreflabel="public.tax_extended">
        <title id="public.table.tax-extended-title">
         Table:
         <database class="view">tax_extended</database>
         
        </title>
 

        <para>
           This stores extended information for manual tax calculations.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">tax_extended</database>
            </title>


            <varlistentry>
              <term><database class="field">tax_basis</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">rate</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.acc-trans"/></database>




              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.taxcategory"
               xreflabel="public.taxcategory">
        <title id="public.table.taxcategory-title">
         Table:
         <database class="view">taxcategory</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">taxcategory</database>
            </title>


            <varlistentry>
              <term><database class="field">taxcategory_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxcategoryname</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxmodule_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.taxmodule"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing partstax via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.partstax"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.taxmodule"
               xreflabel="public.taxmodule">
        <title id="public.table.taxmodule-title">
         Table:
         <database class="view">taxmodule</database>
         
        </title>
 

        <para>
          This is used to store information on tax modules.  the module name is used
to determine the Perl class for the taxes.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">taxmodule</database>
            </title>


            <varlistentry>
              <term><database class="field">taxmodule_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">taxmodulename</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing tax via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.tax"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.taxcategory"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.template"
               xreflabel="public.template">
        <title id="public.table.template-title">
         Table:
         <database class="view">template</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">template</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">template_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>








                <database class="constraint">UNIQUE#1</database>









                <database class="constraint">REFERENCES <xref linkend="public.table.language"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">template</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>





              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">format</database></term>
              <listitem><para>
                <database class="datatype">text</database>




                <database class="constraint">UNIQUE#1</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">last_modified</database></term>
              <listitem><para>
                <database class="datatype">timestamp with time zone</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT now()</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.transactions"
               xreflabel="public.transactions">
        <title id="public.table.transactions-title">
         Table:
         <database class="view">transactions</database>
         
        </title>
 

        <para>
           This table provides referential integrity between AR, AP, GL tables on one
hand and acc_trans on the other, pending the refactoring of those tables.  It
also is used to provide discretionary locking of financial transactions across
database connections, for example in batch payment workflows.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">transactions</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">table_name</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">locked_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.session"/></database>


              </para>

              <para> This should only be used in pessimistic locking measures as required by large
batch work flows. </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_by</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved_at</database></term>
              <listitem><para>
                <database class="datatype">timestamp without time zone</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on transactions</title>

          <varlistentry>
            <term>transactions_locked_by_i</term>
            <listitem><para>locked_by</para></listitem>
          </varlistentry>

        </variablelist>





        <itemizedlist>
          <title>
            Tables referencing acc_trans via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.acc-trans"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.ap"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.ar"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.file-transaction"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.gl"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.invoice"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.new-shipto"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.recurring"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.voucher"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.translation"
               xreflabel="public.translation">
        <title id="public.table.translation-title">
         Table:
         <database class="view">translation</database>
         
        </title>
 

        <para>
          abstract table for manual translation data. Should have zero rows.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">translation</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language_code</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>





        <variablelist>
          <title>Indexes on translation</title>

          <varlistentry>
            <term>translation_trans_id_key</term>
            <listitem><para>trans_id</para></listitem>
          </varlistentry>

        </variablelist>








      </para>
    </section>

      <section id="public.table.trial-balance-yearend-types"
               xreflabel="public.trial_balance__yearend_types">
        <title id="public.table.trial-balance-yearend-types-title">
         Table:
         <database class="view">trial_balance__yearend_types</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">trial_balance__yearend_types</database>
            </title>


            <varlistentry>
              <term><database class="field">type</database></term>
              <listitem><para>
                <database class="datatype">text</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.view.tx-report"
               xreflabel="public.tx_report">
        <title id="public.view.tx-report-title">
         View:
         <database class="table">tx_report</database>
         
        </title>
 

        <para>
           This view provides join and approval information for transactions.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">tx_report</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reference</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_credit_account</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">table</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">approved</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view tx_report</title>
         <programlisting>
SELECT gl.id
,
    gl.reference
,
    NULL::integer AS entity_credit_account
,
    &apos;gl&apos;::text AS &quot;table&quot;
,
    gl.approved
   
FROM gl

UNION ALL
 
SELECT ap.id
,
    ap.invnumber AS reference
,
    ap.entity_credit_account
,
    &apos;ap&apos;::text AS &quot;table&quot;
,
    ap.approved
   
FROM ap

UNION ALL
 
SELECT ar.id
,
    ar.invnumber AS reference
,
    ar.entity_credit_account
,
    &apos;ar&apos;::text AS &quot;table&quot;
,
    ar.approved
   
FROM ar;</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.view.user-listable"
               xreflabel="public.user_listable">
        <title id="public.view.user-listable-title">
         View:
         <database class="table">user_listable</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">user_listable</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">username</database></term>
              <listitem><para>
                <database class="datatype">character varying(30)</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">created</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>








        <figure>
         <title>Definition of view user_listable</title>
         <programlisting>
SELECT u.id
,
    u.username
,
    e.created
   
FROM (entity e
     
  JOIN users u 
    ON (
           (u.entity_id = e.id)
     )
);</programlisting>
        </figure>



      </para>
    </section>

      <section id="public.table.user-preference"
               xreflabel="public.user_preference">
        <title id="public.table.user-preference-title">
         Table:
         <database class="view">user_preference</database>
         
        </title>
 

        <para>
           This table sets the basic preferences for formats, languages, printers, and user-selected stylesheets.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">user_preference</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>






                <database class="constraint">PRIMARY KEY</database>











                <database class="constraint">REFERENCES <xref linkend="public.table.users"/></database>




              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">language</database></term>
              <listitem><para>
                <database class="datatype">character varying(6)</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.language"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">stylesheet</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;ledgersmb.css&apos;::text</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">printer</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">dateformat</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;yyyy-mm-dd&apos;::text</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">numberformat</database></term>
              <listitem><para>
                <database class="datatype">text</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;1000.00&apos;::text</literal>



              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.users"
               xreflabel="public.users">
        <title id="public.table.users-title">
         Table:
         <database class="view">users</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">users</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>




                <database class="constraint">UNIQUE</database>




                <database class="constraint">NOT NULL</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">username</database></term>
              <listitem><para>
                <database class="datatype">character varying(30)</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">notify_password</database></term>
              <listitem><para>
                <database class="datatype">interval</database>



                <database class="constraint">NOT NULL</database>



                <literal>DEFAULT &apos;7 days&apos;::interval</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.entity"/></database>


              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing session via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.session"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.user-preference"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.voucher"
               xreflabel="public.voucher">
        <title id="public.table.voucher-title">
         Table:
         <database class="view">voucher</database>
         
        </title>
 

        <para>
          Mapping transactions to batches for batch approval.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">voucher</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.transactions"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">batch_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.batch"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

              <para> This is simply a surrogate key for easy reference.</para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">batch_class</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







                <database class="constraint">NOT NULL</database>






                <database class="constraint">REFERENCES <xref linkend="public.table.batch-class"/></database>


              </para>

              <para> This is the authoritative class of the
voucher. </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing acc_trans via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.acc-trans"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.warehouse"
               xreflabel="public.warehouse">
        <title id="public.table.warehouse-title">
         Table:
         <database class="view">warehouse</database>
         
        </title>
 


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">warehouse</database>
            </title>


            <varlistentry>
              <term><database class="field">id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">description</database></term>
              <listitem><para>
                <database class="datatype">text</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>







        <itemizedlist>
          <title>
            Tables referencing asset_item via Foreign Key Constraints
          </title>

          <listitem>
            <para>
              <xref linkend="public.table.asset-item"/>
            </para>
          </listitem>



          <listitem>
            <para>
              <xref linkend="public.table.asset-report-line"/>
            </para>
          </listitem>

        </itemizedlist>






      </para>
    </section>

      <section id="public.table.warehouse-inventory"
               xreflabel="public.warehouse_inventory">
        <title id="public.table.warehouse-inventory-title">
         Table:
         <database class="view">warehouse_inventory</database>
         
        </title>
 

        <para>
           This table contains inventory mappings to warehouses, not general inventory
management data.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">warehouse_inventory</database>
            </title>


            <varlistentry>
              <term><database class="field">entity_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>












                <database class="constraint">REFERENCES <xref linkend="public.table.entity-employee"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">warehouse_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">parts_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">orderitems_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">qty</database></term>
              <listitem><para>
                <database class="datatype">numeric</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">shippingdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">entry_id</database></term>
              <listitem><para>
                <database class="datatype">serial</database>


                <database class="constraint">PRIMARY KEY</database>












              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>

      <section id="public.table.yearend"
               xreflabel="public.yearend">
        <title id="public.table.yearend-title">
         Table:
         <database class="view">yearend</database>
         
        </title>
 

        <para>
           An extension to the journal_entry table to track transactionsactions which close out
the books at yearend.
        </para>


        <para>
          <variablelist>
            <title>
              Structure of <database class="table">yearend</database>
            </title>


            <varlistentry>
              <term><database class="field">trans_id</database></term>
              <listitem><para>
                <database class="datatype">integer</database>


                <database class="constraint">PRIMARY KEY</database>

















                <database class="constraint">REFERENCES <xref linkend="public.table.gl"/></database>


              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">reversed</database></term>
              <listitem><para>
                <database class="datatype">boolean</database>





                <literal>DEFAULT false</literal>



              </para>

            </listitem>
          </varlistentry>

            <varlistentry>
              <term><database class="field">transdate</database></term>
              <listitem><para>
                <database class="datatype">date</database>







              </para>

            </listitem>
          </varlistentry>

        </variablelist>










      </para>
    </section>



<!-- Function _entity_location_save(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer) -->
    <section id="public.function.-entity-location-save-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.-entity-location-save-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-title">
       _entity_location_save(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer)
      </title>
      <titleabbrev id="public.function.-entity-location-save-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-titleabbrev">
       _entity_location_save(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Private method for storing locations to an entity.  Do not call directly.
Returns the location id that was inserted or updated.
        <programlisting>

    DECLARE
        l_row location;
        l_id INT;
        t_company_id int;
    BEGIN
        SELECT id INTO t_company_id
        FROM company WHERE entity_id = in_entity_id;

        DELETE FROM entity_to_location
        WHERE entity_id = in_entity_id
                AND location_class = in_location_class
                AND location_id = in_location_id;

        SELECT location_save(NULL, in_line_one, in_line_two, in_line_three, in_city,
                in_state, in_mail_code, in_country_id)
        INTO l_id;

        INSERT INTO entity_to_location
                (entity_id, location_class, location_id)
        VALUES  (in_entity_id, in_location_class, l_id);

        RETURN l_id;
    END;

</programlisting>
      </para>
    </section>

<!-- Function account__all_headings() -->
    <section id="public.function.account-all-headings"
             xreflabel="()">
      <title id="public.function.account-all-headings-title">
       account__all_headings()
      </title>
      <titleabbrev id="public.function.account-all-headings-titleabbrev">
       account__all_headings()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_heading</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM account_heading ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function account__delete(in_id integer) -->
    <section id="public.function.account-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-delete-in-id-integer-title">
       account__delete(in_id integer)
      </title>
      <titleabbrev id="public.function.account-delete-in-id-integer-titleabbrev">
       account__delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This deletes an account with the id specified.  If the account has
transactions associated with it, it will fail and raise a foreign key constraint.

        <programlisting>
BEGIN
DELETE FROM tax WHERE chart_id = in_id;
DELETE FROM account_link WHERE account_id = in_id;
DELETE FROM account WHERE id = in_id;
RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function account__delete_translation(in_id integer, in_language_code text) -->
    <section id="public.function.account-delete-translation-in-id-integer-in-language-code-text"
             xreflabel="()">
      <title id="public.function.account-delete-translation-in-id-integer-in-language-code-text-title">
       account__delete_translation(in_id integer, in_language_code text)
      </title>
      <titleabbrev id="public.function.account-delete-translation-in-id-integer-in-language-code-text-titleabbrev">
       account__delete_translation(in_id integer, in_language_code text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
       Deletes the translation for the account+language combination.
        <programlisting>
   DELETE FROM account_translation
    WHERE trans_id = $1
      AND language_code = $2;
</programlisting>
      </para>
    </section>

<!-- Function account__get_by_accno(in_accno text) -->
    <section id="public.function.account-get-by-accno-in-accno-text"
             xreflabel="()">
      <title id="public.function.account-get-by-accno-in-accno-text-title">
       account__get_by_accno(in_accno text)
      </title>
      <titleabbrev id="public.function.account-get-by-accno-in-accno-text-titleabbrev">
       account__get_by_accno(in_accno text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM account WHERE accno = $1;
</programlisting>
      </para>
    </section>

<!-- Function account__get_by_link_desc(in_description text) -->
    <section id="public.function.account-get-by-link-desc-in-description-text"
             xreflabel="()">
      <title id="public.function.account-get-by-link-desc-in-description-text-title">
       account__get_by_link_desc(in_description text)
      </title>
      <titleabbrev id="public.function.account-get-by-link-desc-in-description-text-titleabbrev">
       account__get_by_link_desc(in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Gets a list of accounts with a specific link description set.  For example,
for a dropdown list.
        <programlisting>
SELECT * FROM account
WHERE id IN (SELECT account_id FROM account_link WHERE description = $1);
</programlisting>
      </para>
    </section>

<!-- Function account__get_from_accno(in_accno text) -->
    <section id="public.function.account-get-from-accno-in-accno-text"
             xreflabel="()">
      <title id="public.function.account-get-from-accno-in-accno-text-title">
       account__get_from_accno(in_accno text)
      </title>
      <titleabbrev id="public.function.account-get-from-accno-in-accno-text-titleabbrev">
       account__get_from_accno(in_accno text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the account where the accno field matches (excatly) the
in_accno provided.
        <programlisting>
     select * from account where accno = $1;
</programlisting>
      </para>
    </section>

<!-- Function account__get_taxes() -->
    <section id="public.function.account-get-taxes"
             xreflabel="()">
      <title id="public.function.account-get-taxes-title">
       account__get_taxes()
      </title>
      <titleabbrev id="public.function.account-get-taxes-titleabbrev">
       account__get_taxes()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns set of accounts where the tax attribute is true.
        <programlisting>
SELECT * FROM account
 WHERE tax is true
ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function account__is_recon(in_accno text) -->
    <section id="public.function.account-is-recon-in-accno-text"
             xreflabel="()">
      <title id="public.function.account-is-recon-in-accno-text-title">
       account__is_recon(in_accno text)
      </title>
      <titleabbrev id="public.function.account-is-recon-in-accno-text-titleabbrev">
       account__is_recon(in_accno text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if account is set up for reconciliation, false otherwise.
Note that returns false on invalid account number too
        <programlisting> SELECT count(*) &gt; 0
     FROM cr_coa_to_account c2a
     JOIN account ON account.id = c2a.chart_id
    WHERE accno = $1; </programlisting>
      </para>
    </section>

<!-- Function account__list_by_heading() -->
    <section id="public.function.account-list-by-heading"
             xreflabel="()">
      <title id="public.function.account-list-by-heading-title">
       account__list_by_heading()
      </title>
      <titleabbrev id="public.function.account-list-by-heading-titleabbrev">
       account__list_by_heading()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM account ORDER BY heading;
</programlisting>
      </para>
    </section>

<!-- Function account__list_translations(in_id integer) -->
    <section id="public.function.account-list-translations-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-list-translations-in-id-integer-title">
       account__list_translations(in_id integer)
      </title>
      <titleabbrev id="public.function.account-list-translations-in-id-integer-titleabbrev">
       account__list_translations(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_translation</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns the list of translations for the given account.
        <programlisting>
   SELECT * FROM account_translation WHERE trans_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function account__obtain_balance(in_transdate date, in_account_id integer) -->
    <section id="public.function.account-obtain-balance-in-transdate-date-in-account-id-integer"
             xreflabel="()">
      <title id="public.function.account-obtain-balance-in-transdate-date-in-account-id-integer-title">
       account__obtain_balance(in_transdate date, in_account_id integer)
      </title>
      <titleabbrev id="public.function.account-obtain-balance-in-transdate-date-in-account-id-integer-titleabbrev">
       account__obtain_balance(in_transdate date, in_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns the account balance at a given point in time, calculating forward
from most recent check point.  This function is inclusive of in_transdate.  For
an exclusive function see account__obtain_starting_balance below.
        <programlisting>
WITH cp AS (
  SELECT amount, end_date, account_id
    FROM account_checkpoint
   WHERE account_id = in_account_id
     AND end_date &lt;= in_transdate
ORDER BY end_date DESC LIMIT 1
),
ac AS (
  SELECT acc_trans.amount
    FROM acc_trans
    JOIN (select id from ar where approved
          union select id from ap where approved
          union select id from gl where approved) a on acc_trans.trans_id = a.id
  LEFT JOIN cp ON acc_trans.chart_id = cp.account_id
   WHERE (cp.end_date IS NULL OR transdate &gt; cp.end_date)
     AND transdate &lt;= in_transdate
     AND chart_id = in_account_id)

 SELECT coalesce((select sum(amount)
                    from (select sum(amount) as amount from cp
                          union all
                          select sum(amount) from ac) as a),
                 0);
</programlisting>
      </para>
    </section>

<!-- Function account__obtain_starting_balance(in_transdate date, in_account_id integer) -->
    <section id="public.function.account-obtain-starting-balance-in-transdate-date-in-account-id-integer"
             xreflabel="()">
      <title id="public.function.account-obtain-starting-balance-in-transdate-date-in-account-id-integer-title">
       account__obtain_starting_balance(in_transdate date, in_account_id integer)
      </title>
      <titleabbrev id="public.function.account-obtain-starting-balance-in-transdate-date-in-account-id-integer-titleabbrev">
       account__obtain_starting_balance(in_transdate date, in_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT account__obtain_balance($1 - 1, $2);
</programlisting>
      </para>
    </section>

<!-- Function account__save(in_id integer, in_accno text, in_description text, in_category bpchar, in_gifi_accno text, in_heading integer, in_contra boolean, in_tax boolean, in_link text[], in_obsolete boolean, in_is_temp boolean) -->
    <section id="public.function.account-save-in-id-integer-in-accno-text-in-description-text-in-category-bpchar-in-gifi-accno-text-in-heading-integer-in-contra-boolean-in-tax-boolean-in-link-textARRAY-in-obsolete-boolean-in-is-temp-boolean"
             xreflabel="()">
      <title id="public.function.account-save-in-id-integer-in-accno-text-in-description-text-in-category-bpchar-in-gifi-accno-text-in-heading-integer-in-contra-boolean-in-tax-boolean-in-link-textARRAY-in-obsolete-boolean-in-is-temp-boolean-title">
       account__save(in_id integer, in_accno text, in_description text, in_category bpchar, in_gifi_accno text, in_heading integer, in_contra boolean, in_tax boolean, in_link text[], in_obsolete boolean, in_is_temp boolean)
      </title>
      <titleabbrev id="public.function.account-save-in-id-integer-in-accno-text-in-description-text-in-category-bpchar-in-gifi-accno-text-in-heading-integer-in-contra-boolean-in-tax-boolean-in-link-textARRAY-in-obsolete-boolean-in-is-temp-boolean-titleabbrev">
       account__save(in_id integer, in_accno text, in_description text, in_category bpchar, in_gifi_accno text, in_heading integer, in_contra boolean, in_tax boolean, in_link text[], in_obsolete boolean, in_is_temp boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        This deletes existing account_link entries, where the
account_link.description is not designated as a custom one in the
account_link_description table.

If no account heading is provided, the account heading which has an accno field
closest to but prior (by collation order) is used.

Then it saves the account information, and rebuilds the account_link records
based on the in_link array.

        <programlisting>
DECLARE
        t_heading_id int;
        t_link record;
        t_id int;
        t_tax bool;
BEGIN

    SELECT count(*) &gt; 0 INTO t_tax FROM tax WHERE in_id = chart_id;
    t_tax := t_tax OR in_tax;
        -- check to ensure summary accounts are exclusive
        -- necessary for proper handling by legacy code
    FOR t_link IN SELECT description FROM account_link_description
    WHERE summary=&#39;t&#39;
        LOOP
                IF t_link.description = ANY (in_link) and array_upper(in_link, 1) &gt; 1 THEN
                        RAISE EXCEPTION &#39;Invalid link settings:  Summary&#39;;
                END IF;
        END LOOP;
        -- heading settings
        IF in_heading IS NULL THEN
                SELECT id INTO t_heading_id FROM account_heading
                WHERE accno &lt; in_accno order by accno desc limit 1;
        ELSE
                t_heading_id := in_heading;
        END IF;

    -- don&#39;t remove custom links.
        DELETE FROM account_link
        WHERE account_id = in_id
              and description in ( select description
                                    from  account_link_description
                                    where custom = &#39;f&#39;);

        UPDATE account
        SET accno = in_accno,
                description = in_description,
                category = in_category,
                gifi_accno = in_gifi_accno,
                heading = t_heading_id,
                contra = in_contra,
                obsolete = coalesce(in_obsolete,&#39;f&#39;),
                tax = t_tax,
                is_temp = coalesce(in_is_temp,&#39;f&#39;)
        WHERE id = in_id;

        IF FOUND THEN
                t_id := in_id;
        ELSE
                -- can&#39;t obsolete on insert, but this can be changed if users
                -- request it --CT
                INSERT INTO account (accno, description, category, gifi_accno,
                        heading, contra, tax, is_temp)
                VALUES (in_accno, in_description, in_category, in_gifi_accno,
                        t_heading_id, in_contra, in_tax, coalesce(in_is_temp, &#39;f&#39;));

                t_id := currval(&#39;account_id_seq&#39;);
        END IF;

        FOR t_link IN
                select in_link[generate_series] AS val
                FROM generate_series(array_lower(in_link, 1),
                        array_upper(in_link, 1))
        LOOP
                INSERT INTO account_link (account_id, description)
                VALUES (t_id, t_link.val);
        END LOOP;


        RETURN t_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function account__save_tax(in_chart_id integer, in_validto date, in_rate numeric, in_minvalue numeric, in_maxvalue numeric, in_taxnumber text, in_pass integer, in_taxmodule_id integer, in_old_validto date) -->
    <section id="public.function.account-save-tax-in-chart-id-integer-in-validto-date-in-rate-numeric-in-minvalue-numeric-in-maxvalue-numeric-in-taxnumber-text-in-pass-integer-in-taxmodule-id-integer-in-old-validto-date"
             xreflabel="()">
      <title id="public.function.account-save-tax-in-chart-id-integer-in-validto-date-in-rate-numeric-in-minvalue-numeric-in-maxvalue-numeric-in-taxnumber-text-in-pass-integer-in-taxmodule-id-integer-in-old-validto-date-title">
       account__save_tax(in_chart_id integer, in_validto date, in_rate numeric, in_minvalue numeric, in_maxvalue numeric, in_taxnumber text, in_pass integer, in_taxmodule_id integer, in_old_validto date)
      </title>
      <titleabbrev id="public.function.account-save-tax-in-chart-id-integer-in-validto-date-in-rate-numeric-in-minvalue-numeric-in-maxvalue-numeric-in-taxnumber-text-in-pass-integer-in-taxmodule-id-integer-in-old-validto-date-titleabbrev">
       account__save_tax(in_chart_id integer, in_validto date, in_rate numeric, in_minvalue numeric, in_maxvalue numeric, in_taxnumber text, in_pass integer, in_taxmodule_id integer, in_old_validto date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This saves tax rates.
        <programlisting>
BEGIN
        UPDATE tax SET validto = in_validto,
               rate = in_rate,
               minvalue = in_minvalue,
               maxvalue = in_maxvalue,
               taxnumber = in_taxnumber,
               pass = in_pass,
               taxmodule_id = in_taxmodule_id
         WHERE chart_id = in_chart_id and validto = in_old_validto;

         IF FOUND THEN
             return true;
         END IF;

         INSERT INTO tax(chart_id, validto, rate, minvalue, maxvalue, taxnumber,
                        pass, taxmodule_id)
         VALUES (in_chart_id, in_validto, in_rate, in_minvalue, in_maxvalue,
                in_taxnumber, in_pass, in_taxmodule_id);

         RETURN TRUE;

END;
</programlisting>
      </para>
    </section>

<!-- Function account__save_translation(in_id integer, in_language_code text, in_description text) -->
    <section id="public.function.account-save-translation-in-id-integer-in-language-code-text-in-description-text"
             xreflabel="()">
      <title id="public.function.account-save-translation-in-id-integer-in-language-code-text-in-description-text-title">
       account__save_translation(in_id integer, in_language_code text, in_description text)
      </title>
      <titleabbrev id="public.function.account-save-translation-in-id-integer-in-language-code-text-in-description-text-titleabbrev">
       account__save_translation(in_id integer, in_language_code text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
       Saves the translation for the given account, creating a new
translation if none existed for the account+language combination.
        <programlisting>
BEGIN
   UPDATE account_translation
      SET description = in_description
    WHERE language_code = in_language_code
      AND trans_id = in_id;

   IF NOT FOUND THEN
      INSERT INTO account_translation
             (trans_id, language_code, description)
      VALUES (in_id, in_language_code, in_description);
   END IF;
   RETURN;
END;</programlisting>
      </para>
    </section>

<!-- Function account_get(in_id integer) -->
    <section id="public.function.account-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-get-in-id-integer-title">
       account_get(in_id integer)
      </title>
      <titleabbrev id="public.function.account-get-in-id-integer-titleabbrev">
       account_get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>chart</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns an entry from the chart view which matches the id requested, and which
is an account, not a heading.
        <programlisting>
select c.id, c.accno, c.description,
       &#39;A&#39;::text as charttype, c.category, concat_colon(l.description) as link,
       heading, gifi_accno, contra, tax
  from account c
  left join account_link l
    ON (c.id = l.account_id)
  where  id = $1
group by c.id, c.accno, c.description, c.category,
         c.heading, c.gifi_accno, c.contra, c.tax;
</programlisting>
      </para>
    </section>

<!-- Function account_has_transactions(in_id integer) -->
    <section id="public.function.account-has-transactions-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-has-transactions-in-id-integer-title">
       account_has_transactions(in_id integer)
      </title>
      <titleabbrev id="public.function.account-has-transactions-in-id-integer-titleabbrev">
       account_has_transactions(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Checks to see if any transactions use this account.  If so, returns true.
If not, returns false.
        <programlisting>
BEGIN
        PERFORM trans_id FROM acc_trans WHERE chart_id = in_id LIMIT 1;
        IF FOUND THEN
                RETURN true;
        ELSE
                RETURN false;
        END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function account_heading__check_tree() -->
    <section id="public.function.account-heading-check-tree"
             xreflabel="()">
      <title id="public.function.account-heading-check-tree-title">
       account_heading__check_tree()
      </title>
      <titleabbrev id="public.function.account-heading-check-tree-titleabbrev">
       account_heading__check_tree()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN

PERFORM * from (
  WITH RECURSIVE account_headings AS (
      SELECT id, accno, 1 as level, accno as path
        FROM account_heading
      UNION ALL
      SELECT ah.id, ah.accno, at.level + 1 as level, at.path  || &#39;||||&#39; || ah.accno
        FROM account_heading ah
        JOIN account_headings at ON ah.parent_id = at.id
       WHERE NOT ah.accno = ANY(string_to_array(path, &#39;||||&#39;))
  )
  SELECT *
    FROM account_heading ah
    JOIN account_headings at ON ah.parent_id = at.id
   WHERE at.path || &#39;||||&#39; ||  ah.accno NOT IN
          (select path from account_headings)
) x;

IF found then
   RAISE EXCEPTION &#39;ACCOUNT_HEADING_LOOP&#39;;
END IF;

RETURN NEW;
end;
</programlisting>
      </para>
    </section>

<!-- Function account_heading__delete(in_id integer) -->
    <section id="public.function.account-heading-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-heading-delete-in-id-integer-title">
       account_heading__delete(in_id integer)
      </title>
      <titleabbrev id="public.function.account-heading-delete-in-id-integer-titleabbrev">
       account_heading__delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This deletes an account heading with the id specified.  If the heading has
accounts associated with it, it will fail and raise a foreign key constraint.

        <programlisting>
BEGIN
DELETE FROM account_heading WHERE id = in_id;
RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function account_heading__delete_translation(in_id integer, in_language_code text) -->
    <section id="public.function.account-heading-delete-translation-in-id-integer-in-language-code-text"
             xreflabel="()">
      <title id="public.function.account-heading-delete-translation-in-id-integer-in-language-code-text-title">
       account_heading__delete_translation(in_id integer, in_language_code text)
      </title>
      <titleabbrev id="public.function.account-heading-delete-translation-in-id-integer-in-language-code-text-titleabbrev">
       account_heading__delete_translation(in_id integer, in_language_code text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
       Deletes the translation for the account+language combination.
        <programlisting>
   DELETE FROM account_heading_translation
    WHERE trans_id = $1
      AND language_code = $2;
</programlisting>
      </para>
    </section>

<!-- Function account_heading__list() -->
    <section id="public.function.account-heading-list"
             xreflabel="()">
      <title id="public.function.account-heading-list-title">
       account_heading__list()
      </title>
      <titleabbrev id="public.function.account-heading-list-titleabbrev">
       account_heading__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_heading</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of all account headings, currently ordered by account number.

        <programlisting> SELECT * FROM account_heading order by accno; </programlisting>
      </para>
    </section>

<!-- Function account_heading__list_translations(in_id integer) -->
    <section id="public.function.account-heading-list-translations-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-heading-list-translations-in-id-integer-title">
       account_heading__list_translations(in_id integer)
      </title>
      <titleabbrev id="public.function.account-heading-list-translations-in-id-integer-titleabbrev">
       account_heading__list_translations(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_heading_translation</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns the list of translations for the given account.
        <programlisting>
   SELECT * FROM account_heading_translation WHERE trans_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function account_heading__save_translation(in_id integer, in_language_code text, in_description text) -->
    <section id="public.function.account-heading-save-translation-in-id-integer-in-language-code-text-in-description-text"
             xreflabel="()">
      <title id="public.function.account-heading-save-translation-in-id-integer-in-language-code-text-in-description-text-title">
       account_heading__save_translation(in_id integer, in_language_code text, in_description text)
      </title>
      <titleabbrev id="public.function.account-heading-save-translation-in-id-integer-in-language-code-text-in-description-text-titleabbrev">
       account_heading__save_translation(in_id integer, in_language_code text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
       Saves the translation for the given account, creating a new
translation if none existed for the account+language combination.
        <programlisting>
BEGIN
   UPDATE account_heading_translation
      SET description = in_description
    WHERE language_code = in_language_code
      AND trans_id = in_id;

   IF NOT FOUND THEN
      INSERT INTO account_heading_translation
             (trans_id, language_code, description)
      VALUES (in_id, in_language_code, in_description);
   END IF;
   RETURN;
END;</programlisting>
      </para>
    </section>

<!-- Function account_heading_get(in_id integer) -->
    <section id="public.function.account-heading-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.account-heading-get-in-id-integer-title">
       account_heading_get(in_id integer)
      </title>
      <titleabbrev id="public.function.account-heading-get-in-id-integer-titleabbrev">
       account_heading_get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>chart</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns an entry from the chart view which matches the id requested, and which
is a heading, not an account.
        <programlisting>
SELECT ah.id, ah.accno, ah.description,
       &#39;H&#39;::text as charttype, NULL::char as category, null::text as link,
       ah.parent_id as account_heading,
       null::text as gifi_accno, false as contra,
       false as tax
   from account_heading ah
  WHERE id = in_id;
</programlisting>
      </para>
    </section>

<!-- Function account_heading_list() -->
    <section id="public.function.account-heading-list"
             xreflabel="()">
      <title id="public.function.account-heading-list-title">
       account_heading_list()
      </title>
      <titleabbrev id="public.function.account-heading-list-titleabbrev">
       account_heading_list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_heading</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all existing account headings.
        <programlisting>
SELECT * FROM account_heading order by accno;
</programlisting>
      </para>
    </section>

<!-- Function account_heading_save(in_id integer, in_accno text, in_description text, in_parent integer) -->
    <section id="public.function.account-heading-save-in-id-integer-in-accno-text-in-description-text-in-parent-integer"
             xreflabel="()">
      <title id="public.function.account-heading-save-in-id-integer-in-accno-text-in-description-text-in-parent-integer-title">
       account_heading_save(in_id integer, in_accno text, in_description text, in_parent integer)
      </title>
      <titleabbrev id="public.function.account-heading-save-in-id-integer-in-accno-text-in-description-text-in-parent-integer-titleabbrev">
       account_heading_save(in_id integer, in_accno text, in_description text, in_parent integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves an account heading. 
        <programlisting>
BEGIN
        UPDATE account_heading
        SET accno = in_accno,
                description = in_description,
                parent_id = in_parent
        WHERE id = in_id;

        IF FOUND THEN
                RETURN in_id;
        END IF;
        INSERT INTO account_heading (accno, description, parent_id)
        VALUES (in_accno, in_description, in_parent);

        RETURN currval(&#39;account_heading_id_seq&#39;);
END;
</programlisting>
      </para>
    </section>

<!-- Function add_custom_field(table_name character varying, new_field_name character varying, field_datatype character varying) -->
    <section id="public.function.add-custom-field-table-name-character-varying-new-field-name-character-varying-field-datatype-character-varying"
             xreflabel="()">
      <title id="public.function.add-custom-field-table-name-character-varying-new-field-name-character-varying-field-datatype-character-varying-title">
       add_custom_field(table_name character varying, new_field_name character varying, field_datatype character varying)
      </title>
      <titleabbrev id="public.function.add-custom-field-table-name-character-varying-new-field-name-character-varying-field-datatype-character-varying-titleabbrev">
       add_custom_field(table_name character varying, new_field_name character varying, field_datatype character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
        perform TABLE_ID FROM custom_table_catalog
                WHERE extends = table_name;
        IF NOT FOUND THEN
                BEGIN
                        INSERT INTO custom_table_catalog (extends)
                                VALUES (table_name);
                        EXECUTE &#39;CREATE TABLE &#39; ||
                               quote_ident(&#39;custom_&#39; ||table_name) ||
                                &#39; (row_id INT PRIMARY KEY)&#39;;
                EXCEPTION WHEN duplicate_table THEN
                        -- do nothing
                END;
        END IF;
        INSERT INTO custom_field_catalog (field_name, table_id)
        values (new_field_name, (SELECT table_id
                                        FROM custom_table_catalog
                WHERE extends = table_name));
        EXECUTE &#39;ALTER TABLE &#39;|| quote_ident(&#39;custom_&#39;||table_name) ||
                &#39; ADD COLUMN &#39; || quote_ident(new_field_name) || &#39; &#39; ||
                  quote_ident(field_datatype);
        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function admin__add_function_to_group(in_func text, in_role text) -->
    <section id="public.function.admin-add-function-to-group-in-func-text-in-role-text"
             xreflabel="()">
      <title id="public.function.admin-add-function-to-group-in-func-text-in-role-text-title">
       admin__add_function_to_group(in_func text, in_role text)
      </title>
      <titleabbrev id="public.function.admin-add-function-to-group-in-func-text-in-role-text-titleabbrev">
       admin__add_function_to_group(in_func text, in_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    declare
        stmt TEXT;
        a_role name;
        a_user name;
    BEGIN

        -- Issue the grant
        select rolname into a_role from pg_roles where rolname = in_role;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot grant permissions of a non-existant role.&#39;;
        END IF;

        select rolname into a_user from pg_roles where rolname = in_username;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot grant permissions to a non-existant user.&#39;;
        END IF;

        stmt := &#39;GRANT EXECUTE ON FUNCTION &#39;|| quote_ident(in_func) ||&#39; to &#39;|| quote_ident(in_role);

        EXECUTE stmt;

        return 1;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__add_group_to_role(in_group_name text, in_role_name text) -->
    <section id="public.function.admin-add-group-to-role-in-group-name-text-in-role-name-text"
             xreflabel="()">
      <title id="public.function.admin-add-group-to-role-in-group-name-text-in-role-name-text-title">
       admin__add_group_to_role(in_group_name text, in_role_name text)
      </title>
      <titleabbrev id="public.function.admin-add-group-to-role-in-group-name-text-in-role-name-text-titleabbrev">
       admin__add_group_to_role(in_group_name text, in_role_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This function inserts the arguments into lsmb_group_grants for future
reference and issues the db-level grant.  It then returns true if there are no
exceptions.
        <programlisting>
DECLARE
   t_group_name text;
   t_role_name  text;
BEGIN
   t_group_name := lsmb__role(in_group_name);
   t_role_name := lsmb__role(in_role_name);
   PERFORM * FROM lsmb_group_grants
     WHERE group_name = t_group_name AND
           granted_role = t_role_name;

   IF NOT FOUND THEN
      INSERT INTO lsmb_group_grants(group_name, granted_role)
           VALUES (t_group_name, t_role_name);
   END IF;

   EXECUTE &#39;GRANT &#39; || quote_ident(t_role_name) || &#39; TO &#39; ||
           quote_literal(t_group_name);
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function admin__add_user_to_role(in_username text, in_role text) -->
    <section id="public.function.admin-add-user-to-role-in-username-text-in-role-text"
             xreflabel="()">
      <title id="public.function.admin-add-user-to-role-in-username-text-in-role-text-title">
       admin__add_user_to_role(in_username text, in_role text)
      </title>
      <titleabbrev id="public.function.admin-add-user-to-role-in-username-text-in-role-text-titleabbrev">
       admin__add_user_to_role(in_username text, in_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    declare
        stmt TEXT;
        a_role name;
        a_user name;
        t_userid int;
    BEGIN

        -- Issue the grant
        select rolname into a_role from pg_roles where rolname = in_role;
        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot grant permissions of a non-existant role.&#39;;
        END IF;

        select rolname into a_user from pg_roles where rolname = in_username;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot grant permissions to a non-existant database user.&#39;;
        END IF;

        stmt := &#39;GRANT &#39;|| quote_ident(in_role) ||&#39; to &#39;|| quote_ident(in_username);

        EXECUTE stmt;

        select id into t_userid from users where username = in_username;
        if not FOUND then
          RAISE EXCEPTION &#39;Cannot grant permissions to a non-existant application user.&#39;;
        end if;

        return 1;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__create_group(in_group_name text) -->
    <section id="public.function.admin-create-group-in-group-name-text"
             xreflabel="()">
      <title id="public.function.admin-create-group-in-group-name-text-title">
       admin__create_group(in_group_name text)
      </title>
      <titleabbrev id="public.function.admin-create-group-in-group-name-text-titleabbrev">
       admin__create_group(in_group_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    DECLARE
        stmt text;
        group_name text;
    BEGIN
        group_name := lsmb__role(in_group_name);
        stmt := &#39;create role &#39;|| quote_ident(group_name);
        execute stmt;
        INSERT INTO lsmb_group (role_name)
             values (group_name);
        return 1;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__delete_group(in_group_name text) -->
    <section id="public.function.admin-delete-group-in-group-name-text"
             xreflabel="()">
      <title id="public.function.admin-delete-group-in-group-name-text-title">
       admin__delete_group(in_group_name text)
      </title>
      <titleabbrev id="public.function.admin-delete-group-in-group-name-text-titleabbrev">
       admin__delete_group(in_group_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
    Deletes the input group from the database. Not designed to be used to
    remove a login-capable user.

        <programlisting>

    DECLARE
        stmt text;
        a_role role_view;
        group_name text;
    BEGIN
        select * into a_role from role_view where rolname = in_group_name;

        if not found then
            return &#39;f&#39;::bool;
        else
            group_name := lsmb__role(in_group_name);
            stmt := &#39;drop role lsmb_&#39; || quote_ident(group_name);
            execute stmt;
            return &#39;t&#39;::bool;
        end if;
    END;
</programlisting>
      </para>
    </section>

<!-- Function admin__delete_user(in_username text, in_drop_role boolean) -->
    <section id="public.function.admin-delete-user-in-username-text-in-drop-role-boolean"
             xreflabel="()">
      <title id="public.function.admin-delete-user-in-username-text-in-drop-role-boolean-title">
       admin__delete_user(in_username text, in_drop_role boolean)
      </title>
      <titleabbrev id="public.function.admin-delete-user-in-username-text-in-drop-role-boolean-titleabbrev">
       admin__delete_user(in_username text, in_drop_role boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
    Drops the provided user, as well as deletes the user configuration data.
It leaves the entity and person references.

If in_drop_role is set, it drops the role too.

        <programlisting>

    DECLARE
        stmt text;
        a_user users;
    BEGIN

        select * into a_user from users where username = in_username;

        IF NOT FOUND THEN

            raise exception &#39;User not found.&#39;;
        ELSIF FOUND THEN
            IF in_drop_role IS TRUE then
                stmt := &#39; drop user &#39; || quote_ident(a_user.username);
                execute stmt;
            END IF;
            -- also gets user_connection
            delete from user_preference where id = (
                   select id from users where entity_id = a_user.entity_id);
            delete from users where entity_id = a_user.entity_id;
            return 1;
        END IF;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__drop_session(in_session_id integer) -->
    <section id="public.function.admin-drop-session-in-session-id-integer"
             xreflabel="()">
      <title id="public.function.admin-drop-session-in-session-id-integer-title">
       admin__drop_session(in_session_id integer)
      </title>
      <titleabbrev id="public.function.admin-drop-session-in-session-id-integer-titleabbrev">
       admin__drop_session(in_session_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Drops the session identified, releasing all locks held.
        <programlisting>
BEGIN
        DELETE FROM &quot;session&quot; WHERE session_id = in_session_id;
        RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function admin__get_roles() -->
    <section id="public.function.admin-get-roles"
             xreflabel="()">
      <title id="public.function.admin-get-roles-title">
       admin__get_roles()
      </title>
      <titleabbrev id="public.function.admin-get-roles-titleabbrev">
       admin__get_roles()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pg_roles</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        SELECT *
        FROM
            pg_roles
        WHERE
            rolname ~ (&#39;^&#39; || lsmb__role_prefix())
            AND NOT rolcanlogin
        ORDER BY rolname ASC
</programlisting>
      </para>
    </section>

<!-- Function admin__get_roles_for_user(in_user_id integer) -->
    <section id="public.function.admin-get-roles-for-user-in-user-id-integer"
             xreflabel="()">
      <title id="public.function.admin-get-roles-for-user-in-user-id-integer-title">
       admin__get_roles_for_user(in_user_id integer)
      </title>
      <titleabbrev id="public.function.admin-get-roles-for-user-in-user-id-integer-titleabbrev">
       admin__get_roles_for_user(in_user_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF text</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a set of roles that  a user is a part of.

Note: this function can only be used by
 - super users
 - database admins (setup.pl users):
   - database owners
   - database users (roles) which were granted the database owner role
 - application users:
   - application admins (users with &apos;manage_users&apos; role)
   - application users (roles) which query their own roles

        <programlisting>

    declare
        u_role record;
        a_user users;
    begin
        select * into a_user from admin__get_user(in_user_id);

        -- this function used to be security definer, but that hides the true
        -- CURRENT_USER, returning the DEFINER instead of the caller
        IF a_user.username != CURRENT_USER THEN
            -- super users and application users match the first criterion
            -- db owners and db owner group members match the second criterion
            IF pg_has_role(lsmb__role(&#39;users_manage&#39;), &#39;USAGE&#39;) IS FALSE
               AND pg_has_role((select rolname
                                 from pg_database db inner join pg_roles rol
                                   on db.datdba = rol.oid
                                where db.datname = current_database()),
                               &#39;USAGE&#39;) IS FALSE THEN
               RAISE EXCEPTION &#39;User % querying permissions for %, not authorised&#39;, CURRENT_USER, a_user.username;
            END IF;
        END IF;

        FOR u_role IN
        select r.rolname
        from
            pg_roles r,
            (select
                m.roleid
             from
                pg_auth_members m, pg_roles b
             where
                m.member = b.oid
             and
                b.rolname = a_user.username
            ) as ar
         where
            r.oid = ar.roleid
            and r.rolname like (lsmb__role_prefix() || &#39;%&#39;)
         LOOP

            RETURN NEXT u_role.rolname::text;

        END LOOP;
        RETURN;
    end;

</programlisting>
      </para>
    </section>

<!-- Function admin__get_roles_for_user_by_entity(in_entity_id integer) -->
    <section id="public.function.admin-get-roles-for-user-by-entity-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.admin-get-roles-for-user-by-entity-in-entity-id-integer-title">
       admin__get_roles_for_user_by_entity(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.admin-get-roles-for-user-by-entity-in-entity-id-integer-titleabbrev">
       admin__get_roles_for_user_by_entity(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF text</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a set of roles that  a user is a part of.

Note: this function can only be used by
 - super users
 - database admins (setup.pl users):
   - database owners
   - database users (roles) which were granted the database owner role
 - application users:
   - application admins (users with &apos;manage_users&apos; role)
   - application users (roles) which query their own roles

        <programlisting>

    declare
        u_role record;
        a_user users;
    begin
        select * into a_user from admin__get_user_by_entity(in_entity_id);

        -- this function used to be security definer, but that hides the true
        -- CURRENT_USER, returning the DEFINER instead of the caller
        IF a_user.username != CURRENT_USER THEN
            -- super users and application users match the first criterion
            -- db owners and db owner group members match the second criterion
            IF pg_has_role(lsmb__role(&#39;users_manage&#39;), &#39;USAGE&#39;) IS FALSE
               AND pg_has_role((select rolname
                                 from pg_database db inner join pg_roles rol
                                   on db.datdba = rol.oid
                                where db.datname = current_database()),
                               &#39;USAGE&#39;) IS FALSE THEN
               RAISE EXCEPTION &#39;User % querying permissions for %, not authorised&#39;, CURRENT_USER, a_user.username;
            END IF;
        END IF;

        FOR u_role IN
        select r.rolname
        from
            pg_roles r,
            (select
                m.roleid
             from
                pg_auth_members m, pg_roles b
             where
                m.member = b.oid
             and
                b.rolname = a_user.username
            ) as ar
         where
            r.oid = ar.roleid
            and r.rolname like (lsmb__role_prefix() || &#39;%&#39;)
         LOOP

            RETURN NEXT u_role.rolname::text;

        END LOOP;
        RETURN;
    end;

</programlisting>
      </para>
    </section>

<!-- Function admin__get_user(in_id integer) -->
    <section id="public.function.admin-get-user-in-id-integer"
             xreflabel="()">
      <title id="public.function.admin-get-user-in-id-integer-title">
       admin__get_user(in_id integer)
      </title>
      <titleabbrev id="public.function.admin-get-user-in-id-integer-titleabbrev">
       admin__get_user(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>users</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of (only one) user specified by the id.
        <programlisting>

        select * from users where id = in_id;

</programlisting>
      </para>
    </section>

<!-- Function admin__get_user_by_entity(in_entity_id integer) -->
    <section id="public.function.admin-get-user-by-entity-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.admin-get-user-by-entity-in-entity-id-integer-title">
       admin__get_user_by_entity(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.admin-get-user-by-entity-in-entity-id-integer-titleabbrev">
       admin__get_user_by_entity(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>users</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of (only one) user specified by the entity_id.
        <programlisting>

        select * from users where entity_id = in_entity_id;

</programlisting>
      </para>
    </section>

<!-- Function admin__is_group(in_group_name text) -->
    <section id="public.function.admin-is-group-in-group-name-text"
             xreflabel="()">
      <title id="public.function.admin-is-group-in-group-name-text-title">
       admin__is_group(in_group_name text)
      </title>
      <titleabbrev id="public.function.admin-is-group-in-group-name-text-titleabbrev">
       admin__is_group(in_group_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    -- This needs some work.  CT
    DECLARE

        existant_role pg_roles;
        stmt text;

    BEGIN
        select * into existant_role from pg_roles
        where rolname = in_group_name AND rolcanlogin is false;

        if not found then
            return &#39;f&#39;::bool;

        else
            return &#39;t&#39;::bool;
        end if;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__is_user(in_user text) -->
    <section id="public.function.admin-is-user-in-user-text"
             xreflabel="()">
      <title id="public.function.admin-is-user-in-user-text-title">
       admin__is_user(in_user text)
      </title>
      <titleabbrev id="public.function.admin-is-user-in-user-text-titleabbrev">
       admin__is_user(in_user text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if user is set up in LedgerSMB.  False otherwise.
        <programlisting>
    BEGIN

        PERFORM * from users where username = in_user;
        RETURN found;

    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__list_group_grants(in_group_name text) -->
    <section id="public.function.admin-list-group-grants-in-group-name-text"
             xreflabel="()">
      <title id="public.function.admin-list-group-grants-in-group-name-text-title">
       admin__list_group_grants(in_group_name text)
      </title>
      <titleabbrev id="public.function.admin-list-group-grants-in-group-name-text-titleabbrev">
       admin__list_group_grants(in_group_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF lsmb_group_grants</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM lsmb_group_grants WHERE group_name = $1
ORDER BY granted_role;
</programlisting>
      </para>
    </section>

<!-- Function admin__list_sessions() -->
    <section id="public.function.admin-list-sessions"
             xreflabel="()">
      <title id="public.function.admin-list-sessions-title">
       admin__list_sessions()
      </title>
      <titleabbrev id="public.function.admin-list-sessions-titleabbrev">
       admin__list_sessions()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF session_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all active sessions.
        <programlisting>
SELECT s.session_id, u.username, s.last_used, count(t.id)
FROM &quot;session&quot; s
JOIN users u ON (s.users_id = u.id)
LEFT JOIN transactions t ON (t.locked_by = s.session_id)
GROUP BY s.session_id, u.username, s.last_used
ORDER BY u.username;
</programlisting>
      </para>
    </section>

<!-- Function admin__remove_function_from_group(in_func text, in_role text) -->
    <section id="public.function.admin-remove-function-from-group-in-func-text-in-role-text"
             xreflabel="()">
      <title id="public.function.admin-remove-function-from-group-in-func-text-in-role-text-title">
       admin__remove_function_from_group(in_func text, in_role text)
      </title>
      <titleabbrev id="public.function.admin-remove-function-from-group-in-func-text-in-role-text-titleabbrev">
       admin__remove_function_from_group(in_func text, in_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    declare
        stmt TEXT;
        a_role name;
        a_user name;
    BEGIN

        -- Issue the grant
        select rolname into a_role from pg_roles where rolname = in_role;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot revoke permissions of non-existant role $.&#39;;
        END IF;

        select rolname into a_user from pg_roles where rolname = in_username;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot revoke permissions from a non-existant function.&#39;;
        END IF;

        stmt := &#39;REVOKE EXECUTE ON FUNCTION &#39;|| quote_ident(in_func) ||&#39; FROM &#39;|| quote_ident(in_role);

        EXECUTE stmt;

        return 1;
    END;


</programlisting>
      </para>
    </section>

<!-- Function admin__remove_group_from_role(in_group_name text, in_role_name text) -->
    <section id="public.function.admin-remove-group-from-role-in-group-name-text-in-role-name-text"
             xreflabel="()">
      <title id="public.function.admin-remove-group-from-role-in-group-name-text-in-role-name-text-title">
       admin__remove_group_from_role(in_group_name text, in_role_name text)
      </title>
      <titleabbrev id="public.function.admin-remove-group-from-role-in-group-name-text-in-role-name-text-titleabbrev">
       admin__remove_group_from_role(in_group_name text, in_role_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
Returns true if the grant record was found and deleted, false otherwise.
Issues db-level revoke in all cases.
        <programlisting>
BEGIN

   EXECUTE &#39;REVOKE &#39; || quote_ident(in_role_name) || &#39; FROM &#39; ||
           quote_literal(&#39;lsmb_&#39; || t_dbname || &#39;__&#39; || in_group_name);

   DELETE FROM lsmb_group_grants
    WHERE group_name = in_group_name AND granted_role = in_role_name;

   RETURN FOUND;

END;

</programlisting>
      </para>
    </section>

<!-- Function admin__remove_user_from_role(in_username text, in_role text) -->
    <section id="public.function.admin-remove-user-from-role-in-username-text-in-role-text"
             xreflabel="()">
      <title id="public.function.admin-remove-user-from-role-in-username-text-in-role-text-title">
       admin__remove_user_from_role(in_username text, in_role text)
      </title>
      <titleabbrev id="public.function.admin-remove-user-from-role-in-username-text-in-role-text-titleabbrev">
       admin__remove_user_from_role(in_username text, in_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    declare
        stmt TEXT;
        a_role name;
        a_user name;
    BEGIN

        -- Issue the grant
        select rolname into a_role from pg_roles where rolname = in_role;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot revoke permissions of a non-existant role.&#39;;
        END IF;

        select rolname into a_user from pg_roles where rolname = in_username;

        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Cannot revoke permissions from a non-existant user.&#39;;
        END IF;

        stmt := &#39;REVOKE &#39;|| quote_ident(in_role) ||&#39; FROM &#39;|| quote_ident(in_username);

        EXECUTE stmt;

        return 1;
    END;

</programlisting>
      </para>
    </section>

<!-- Function admin__save_user(in_id integer, in_entity_id integer, in_username text, in_password text, in_pls_import boolean) -->
    <section id="public.function.admin-save-user-in-id-integer-in-entity-id-integer-in-username-text-in-password-text-in-pls-import-boolean"
             xreflabel="()">
      <title id="public.function.admin-save-user-in-id-integer-in-entity-id-integer-in-username-text-in-password-text-in-pls-import-boolean-title">
       admin__save_user(in_id integer, in_entity_id integer, in_username text, in_password text, in_pls_import boolean)
      </title>
      <titleabbrev id="public.function.admin-save-user-in-id-integer-in-entity-id-integer-in-username-text-in-password-text-in-pls-import-boolean-titleabbrev">
       admin__save_user(in_id integer, in_entity_id integer, in_username text, in_password text, in_pls_import boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Creates a user and relevant records in LedgerSMB and PostgreSQL.
        <programlisting>
    DECLARE

        a_user users;
        v_user_id int;
        p_id int;
        l_id int;
        stmt text;
        t_is_role bool;
        t_is_user bool;
    BEGIN
        -- WARNING TO PROGRAMMERS:  This function runs as the definer and runs
        -- utility statements via EXECUTE.
        -- PLEASE BE VERY CAREFUL ABOUT SQL-INJECTION INSIDE THIS FUNCTION.

       PERFORM rolname FROM pg_roles WHERE rolname = in_username;
       t_is_role := found;
       t_is_user := admin__is_user(in_username);

       IF t_is_role is true and t_is_user is false and in_pls_import is NOT TRUE THEN
          RAISE EXCEPTION &#39;Duplicate user&#39;;
        END IF;

        if t_is_role and in_password is not null then
                execute &#39;ALTER USER &#39; || quote_ident( in_username ) ||
                     &#39; WITH ENCRYPTED PASSWORD &#39; || quote_literal (in_password)
                     || $e$ valid until $e$ ||
                      quote_literal(now() + &#39;1 day&#39;::interval);
        elsif in_pls_import is false AND t_is_user is false
              AND in_password IS NULL THEN
                RAISE EXCEPTION &#39;No password&#39;;
        elsif  t_is_role is false and in_pls_import IS NOT TRUE THEN
            -- create an actual user
                execute &#39;CREATE USER &#39; || quote_ident( in_username ) ||
                     &#39; WITH ENCRYPTED PASSWORD &#39; || quote_literal (in_password)
                     || $e$ valid until $e$ || quote_literal(now() + &#39;1 day&#39;::interval);
       END IF;

        select * into a_user from users lu where lu.id = in_id;
        IF FOUND THEN
            PERFORM admin__add_user_to_role(
                        a_user.username,
                        lsmb__role_prefix() || &#39;base_user&#39;);
            return a_user.id;
        ELSE
            -- Insert cycle

            --- The entity is expected to already BE created. See admin.pm.

            PERFORM * FROM USERS where username = in_username;
            IF NOT FOUND THEN
                v_user_id := nextval(&#39;users_id_seq&#39;);
                insert into users (id, username, entity_id) VALUES (
                    v_user_id,
                    in_username,
                    in_entity_id
                );

                insert into user_preference (id) values (v_user_id);
            END IF;

            IF NOT exists(SELECT * FROM entity_employee WHERE entity_id = in_entity_id) THEN
                INSERT into entity_employee (entity_id) values (in_entity_id);
            END IF;
            -- Finally, issue the create user statement
            PERFORM admin__add_user_to_role(
                        in_username,
                        lsmb__role_prefix() || &#39;base_user&#39;);

            return v_user_id ;



        END IF;

    END;
</programlisting>
      </para>
    </section>

<!-- Function admin__search_users(in_username text, in_first_name text, in_last_name text, in_ssn text, in_dob date) -->
    <section id="public.function.admin-search-users-in-username-text-in-first-name-text-in-last-name-text-in-ssn-text-in-dob-date"
             xreflabel="()">
      <title id="public.function.admin-search-users-in-username-text-in-first-name-text-in-last-name-text-in-ssn-text-in-dob-date-title">
       admin__search_users(in_username text, in_first_name text, in_last_name text, in_ssn text, in_dob date)
      </title>
      <titleabbrev id="public.function.admin-search-users-in-username-text-in-first-name-text-in-last-name-text-in-ssn-text-in-dob-date-titleabbrev">
       admin__search_users(in_username text, in_first_name text, in_last_name text, in_ssn text, in_dob date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF user_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of users matching search criteria.  Nulls match all values.
only username is not an exact match.
        <programlisting>
                SELECT u.id, u.username, p.first_name, p.last_name, e.ssn, e.dob
                FROM users u
                JOIN person p ON (u.entity_id = p.entity_id)
                JOIN entity_employee e ON (e.entity_id = p.entity_id)
                WHERE u.username LIKE &#39;%&#39; || coalesce(in_username,&#39;&#39;) || &#39;%&#39; AND
                        (p.first_name = in_first_name or in_first_name is null)
                        AND (p.last_name = in_last_name or in_last_name is null)
                        AND (in_ssn is NULL or in_ssn = e.ssn)
                        AND (e.dob = in_dob::date or in_dob is NULL)
</programlisting>
      </para>
    </section>

<!-- Function ap_simple_post(in_entity_credit_account integer, in_ap_liablility_chartid integer, in_invnumber text, in_transdate date, in_duedate date, in_curr bpchar, in_description text, in_ordnumber text, in_notes text, in_intnotes text, in_ponumber text, in_memo text[], in_netamount numeric[], in_chartid numeric[], in_taxrate numeric[], in_taxchartid numeric[]) -->
    <section id="public.function.ap-simple-post-in-entity-credit-account-integer-in-ap-liablility-chartid-integer-in-invnumber-text-in-transdate-date-in-duedate-date-in-curr-bpchar-in-description-text-in-ordnumber-text-in-notes-text-in-intnotes-text-in-ponumber-text-in-memo-textARRAY-in-netamount-numericARRAY-in-chartid-numericARRAY-in-taxrate-numericARRAY-in-taxchartid-numericARRAY"
             xreflabel="()">
      <title id="public.function.ap-simple-post-in-entity-credit-account-integer-in-ap-liablility-chartid-integer-in-invnumber-text-in-transdate-date-in-duedate-date-in-curr-bpchar-in-description-text-in-ordnumber-text-in-notes-text-in-intnotes-text-in-ponumber-text-in-memo-textARRAY-in-netamount-numericARRAY-in-chartid-numericARRAY-in-taxrate-numericARRAY-in-taxchartid-numericARRAY-title">
       ap_simple_post(in_entity_credit_account integer, in_ap_liablility_chartid integer, in_invnumber text, in_transdate date, in_duedate date, in_curr bpchar, in_description text, in_ordnumber text, in_notes text, in_intnotes text, in_ponumber text, in_memo text[], in_netamount numeric[], in_chartid numeric[], in_taxrate numeric[], in_taxchartid numeric[])
      </title>
      <titleabbrev id="public.function.ap-simple-post-in-entity-credit-account-integer-in-ap-liablility-chartid-integer-in-invnumber-text-in-transdate-date-in-duedate-date-in-curr-bpchar-in-description-text-in-ordnumber-text-in-notes-text-in-intnotes-text-in-ponumber-text-in-memo-textARRAY-in-netamount-numericARRAY-in-chartid-numericARRAY-in-taxrate-numericARRAY-in-taxchartid-numericARRAY-titleabbrev">
       ap_simple_post(in_entity_credit_account integer, in_ap_liablility_chartid integer, in_invnumber text, in_transdate date, in_duedate date, in_curr bpchar, in_description text, in_ordnumber text, in_notes text, in_intnotes text, in_ponumber text, in_memo text[], in_netamount numeric[], in_chartid numeric[], in_taxrate numeric[], in_taxchartid numeric[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE invnumber text;
DECLARE ap_id   int;
DECLARE entry_id   int;
DECLARE chartid int;
DECLARE tax_chartid int;
DECLARE invoice bool;
DECLARE separate_duties bool;
DECLARE approved bool;
DECLARE taxincluded bool;
DECLARE curr char(3);
DECLARE curr_default char(3);
DECLARE transdate date;
DECLARE duedate date;
DECLARE crdate date;
DECLARE memo text;
DECLARE netamount numeric;
DECLARE netamount_total numeric;
DECLARE taxrate numeric;
DECLARE taxamount numeric;
DECLARE taxamount_total numeric;
DECLARE amount_total numeric;
DECLARE person_id int;
DECLARE dp int;
DECLARE fx_transaction bool;
DECLARE cleared bool;
DECLARE taxform_id int;
DECLARE reportable bool;
DECLARE atf_count int;
DECLARE ect_count int;
BEGIN
 netamount_total=0.0;
 taxamount_total=0.0;
 invoice=false;
 approved=true;
 taxincluded=false;
 fx_transaction=false;
 cleared=false;

 select value::int       INTO dp FROM setting_get(&#39;decimal_places&#39;);
 select person__get_my_entity_id into person_id from person__get_my_entity_id();
 SELECT value::bool INTO separate_duties FROM defaults WHERE setting_key=&#39;separate_duties&#39;;
 IF separate_duties = true THEN
  --RAISE EXCEPTION &#39;separate_duties not yet treated&#39;;
  approved=false;
 END IF;
 select eca.taxform_id::int into taxform_id from entity_credit_account eca where eca.id=in_entity_credit_account;
 IF taxform_id &lt;&gt; 0 THEN
  --FOREIGN KEY (taxform_id) REFERENCES country_tax_form(id)
  RAISE EXCEPTION &#39;taxform not yet treated&#39;;
 END IF;

 transdate=coalesce(in_transdate,&#39;today&#39;);
 duedate=coalesce(in_duedate,&#39;today&#39;);
 crdate=now();

 --IF in_invnumber IS NULL OR (length(trim(in_invnumber))=0) THEN --NULL as only designator for &quot;no value supplied&quot;
 IF in_invnumber IS NULL THEN
  select setting_increment::text INTO invnumber FROM setting_increment(&#39;vinumber&#39;);
 ELSE
  invnumber=in_invnumber;
 END IF;

 select defaults_get_defaultcurrency into curr_default from defaults_get_defaultcurrency();
 IF in_curr IS NULL THEN
  curr=curr_default;
 ELSE
  curr=in_curr;
 END IF;
 IF curr &lt;&gt; curr_default THEN
  RAISE EXCEPTION &#39;curr &lt;&gt; curr_default not yet treated&#39;;
 END IF;

 FOR out_count IN array_lower(in_memo, 1) .. array_upper(in_memo, 1)
 LOOP
   netamount=in_netamount[out_count];
   netamount_total=netamount_total+netamount;
   taxrate=in_taxrate[out_count];
   IF taxrate IS NOT NULL THEN
    taxamount=netamount*taxrate;
   ELSE
    taxamount=0.0;
   END IF;
   taxamount_total=taxamount_total+taxamount;
 END LOOP;

 amount_total=netamount_total+taxamount_total;

 amount_total=round(amount_total,dp);
 netamount_total=round(netamount_total,dp);

 INSERT INTO ap (entity_credit_account,invnumber,transdate,invoice,approved,taxincluded,curr,duedate,crdate,netamount,amount,person_id,description,ordnumber,notes,intnotes,ponumber) VALUES(in_entity_credit_account,invnumber,transdate,invoice,approved,taxincluded,curr,duedate,crdate,netamount_total,amount_total,person_id,in_description,in_ordnumber,in_notes,in_intnotes,in_ponumber);

 SELECT currval(&#39;id&#39;) INTO ap_id;--NOT &quot;id&quot;!

 INSERT INTO acc_trans(trans_id,transdate,chart_id,amount,approved) values(ap_id,transdate,in_ap_liablility_chartid,amount_total,approved);

 FOR out_count IN array_lower(in_memo, 1) .. array_upper(in_memo, 1)
 LOOP
  memo=in_memo[out_count];
  chartid=in_chartid[out_count];
  tax_chartid=in_taxchartid[out_count];
  netamount=in_netamount[out_count];
  taxrate=in_taxrate[out_count];
  taxamount=0.0;
  IF taxrate IS NOT NULL THEN
   IF tax_chartid IS NOT NULL THEN
     select count(*) into ect_count from eca_tax ect where ect.eca_id=in_entity_credit_account and ect.chart_id=tax_chartid;
     IF ect_count = 0 THEN
      RAISE EXCEPTION &#39;tax_chartid NOT IN  eca_tax&#39;;
     END IF;
     taxamount=netamount*taxrate;
     taxamount=round(taxamount,dp);
     INSERT INTO acc_trans (trans_id,chart_id,amount,transdate,fx_transaction,memo) VALUES(ap_id,tax_chartid,taxamount*-1.0,transdate,fx_transaction,memo);
   ELSE --tax_chartid null
    RAISE EXCEPTION &#39;taxrate NOT NULL but tax_chartid NULL&#39;;
   END IF;--tax_chartid
  ELSE --taxrate null
   IF tax_chartid IS NOT NULL THEN
    RAISE EXCEPTION &#39;taxrate NULL but tax_chartid NOT NULL&#39;;
   END IF;
   --taxamount=0.0;
  END IF;--taxrate

  netamount=round(netamount,dp);
  INSERT INTO acc_trans (trans_id,chart_id,amount,transdate,memo,fx_transaction,cleared) VALUES(ap_id,chartid,netamount*-1.0,transdate,memo,fx_transaction,cleared);
  SELECT currval(&#39;acc_trans_entry_id_seq&#39;) INTO entry_id;

  IF taxform_id &lt;&gt; 0 THEN
   select count(*) into atf_count from ac_tax_form atf where atf.entry_id=entry_id;
   IF atf_count &gt; 0 THEN
    update ac_tax_form atf set atf.reportable=reportable where atf.entry_id=entry_id;
   ELSE
    insert into ac_tax_form(entry_id,reportable) values(entry_id,reportable);
   END IF;
  END IF;--taxform_id

 END LOOP;

 PERFORM trans_id FROM acc_trans WHERE trans_id = ap_id GROUP BY trans_id HAVING sum(amount) &lt;&gt; 0;
 IF FOUND THEN
   RAISE EXCEPTION &#39;Out of balance&#39;;
 END IF;

 return ap_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function ar_ap__transaction_search(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean) -->
    <section id="public.function.ar-ap-transaction-search-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.ar-ap-transaction-search-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean-title">
       ar_ap__transaction_search(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean)
      </title>
      <titleabbrev id="public.function.ar-ap-transaction-search-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean-titleabbrev">
       ar_ap__transaction_search(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF purchase_info</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT gl.id, gl.invoice,
          gl.invnumber, gl.ordnumber, gl.ponumber, gl.transdate,
          e.name, eca.meta_number::text, e.id, gl.amount,
          gl.amount - sum(CASE WHEN l.description IN (&#39;AR&#39;, &#39;AP&#39;)
                               THEN ac.amount ELSE 0
                           END),
          gl.amount - gl.netamount, gl.curr, gl.datepaid, gl.duedate,
          gl.notes, gl.shippingpoint, gl.shipvia,
          compound_array(bua.business_units || bui.business_units)
     FROM (select id, invoice, invnumber, ordnumber, ponumber, transdate, duedate,
                  description, notes, shipvia, shippingpoint, amount,
                  netamount, curr, datepaid, entity_credit_account, on_hold,
                  approved
             FROM ar WHERE in_entity_class = 2
            UNION
           select id, invoice, invnumber, ordnumber, ponumber, transdate, duedate,
                  description, notes, shipvia, shippingpoint, amount,
                  netamount, curr, datepaid, entity_credit_account, on_hold,
                  approved
             FROM ap WHERE in_entity_class = 1) gl
     JOIN entity_credit_account eca ON gl.entity_credit_account = eca.id
     JOIN entity e ON e.id = eca.entity_id
     JOIN acc_trans ac ON gl.id = ac.trans_id
     JOIN account act ON act.id = ac.chart_id
LEFT JOIN account_link l ON l.account_id = act.id
                          AND l.description IN (&#39;AR&#39;, &#39;AP&#39;)
LEFT JOIN invoice inv ON gl.id = inv.trans_id
LEFT JOIN (SELECT compound_array(ARRAY[ARRAY[buc.label, bu.control_code]])
                  as business_units, entry_id
             FROM business_unit_class buc
             JOIN business_unit bu ON bu.class_id = buc.id
             JOIN business_unit_ac buac ON buac.bu_id = bu.id
         GROUP BY buac.entry_id) bua
                                 ON bua.entry_id = ac.entry_id
LEFT JOIN (SELECT compound_array(ARRAY[ARRAY[buc.label, bu.control_code]])
                  as business_units, entry_id
             FROM business_unit_class buc
             JOIN business_unit bu ON bu.class_id = buc.id
             JOIN business_unit_inv buinv ON buinv.bu_id = bu.id
         GROUP BY buinv.entry_id) bui
                                 ON bui.entry_id = inv.id
    WHERE (in_account_id IS NULL OR ac.chart_id = in_account_id)
          AND (in_name_part IS NULL
                OR to_tsvector(get_default_lang()::regconfig, e.name)
                   @@ plainto_tsquery(get_default_lang()::regconfig, in_name_part))
          AND (in_meta_number IS NULL
                OR eca.meta_number LIKE in_meta_number || &#39;%&#39;)
          AND (in_invnumber IS NULL or gl.invnumber LIKE in_invnumber || &#39;%&#39;)
          AND (in_ordnumber IS NULL or gl.ordnumber LIKE in_ordnumber || &#39;%&#39;)
          AND (in_ponumber IS NULL or gl.ponumber LIKE in_ponumber || &#39;%&#39;)
          AND (in_description IS NULL
                or to_tsvector(get_default_lang()::regconfig, gl.description)
                  @@ plainto_tsquery(get_default_lang()::regconfig, in_description))
          AND (in_notes IS NULL OR
                to_tsvector(get_default_lang()::regconfig, gl.notes)
                 @@ plainto_tsquery(get_default_lang()::regconfig, in_notes))
          AND (in_from_date IS NULL OR in_from_date &lt;= gl.transdate)
          AND (in_to_date IS NULL OR in_to_date &gt;= gl.transdate)
          AND (in_on_hold IS NULL OR in_on_hold = gl.on_hold)
          AND (in_as_of IS NULL OR in_as_of &gt;= ac.transdate)
          AND (in_approved is null
               OR (gl.approved = in_approved AND ac.approved = in_approved))
 GROUP BY gl.id, gl.invnumber, gl.ordnumber, gl.ponumber, gl.transdate,
          gl.duedate, e.name, eca.meta_number, gl.amount,
          gl.netamount, gl.curr, gl.datepaid, gl.duedate,
          gl.notes, gl.shippingpoint, gl.shipvia, e.id, gl.invoice
   HAVING in_source = ANY(array_agg(ac.source)) or in_source IS NULL;
</programlisting>
      </para>
    </section>

<!-- Function ar_ap__transaction_search_summary(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean) -->
    <section id="public.function.ar-ap-transaction-search-summary-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.ar-ap-transaction-search-summary-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean-title">
       ar_ap__transaction_search_summary(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean)
      </title>
      <titleabbrev id="public.function.ar-ap-transaction-search-summary-in-account-id-integer-in-name-part-text-in-meta-number-text-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-inc-open-boolean-in-inc-closed-boolean-in-as-of-date-in-entity-class-integer-in-approved-boolean-titleabbrev">
       ar_ap__transaction_search_summary(in_account_id integer, in_name_part text, in_meta_number text, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_inc_open boolean, in_inc_closed boolean, in_as_of date, in_entity_class integer, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF purchase_info</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
       SELECT null::int, null::bool, null::text, null::text, null::text,
              null::date, entity_name, meta_number, entity_id, sum(amount),
              sum(amount_paid), sum(tax), currency, null::date, null::date,
              null::text, null::text, null::text, null::text[]
         FROM ar_ap__transaction_search
              (in_account_id, in_name_part, in_meta_number, in_invnumber,
              in_ordnumber, in_ponumber, in_source, in_description,
              in_notes, in_shipvia, in_from_date, in_to_date,
              in_on_hold, in_inc_open, in_inc_closed, in_as_of,
              in_entity_class, in_approved)
     GROUP BY entity_name, meta_number, entity_id, currency;
</programlisting>
      </para>
    </section>

<!-- Function array_endswith(elem anyelement, arr anyarray) -->
    <section id="public.function.array-endswith-elem-anyelement-arr-anyarray"
             xreflabel="()">
      <title id="public.function.array-endswith-elem-anyelement-arr-anyarray-title">
       array_endswith(elem anyelement, arr anyarray)
      </title>
      <titleabbrev id="public.function.array-endswith-elem-anyelement-arr-anyarray-titleabbrev">
       array_endswith(elem anyelement, arr anyarray)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT $2[array_upper($2,1)]=$1;
</programlisting>
      </para>
    </section>

<!-- Function array_splice_from(elem anyelement, arr anyarray) -->
    <section id="public.function.array-splice-from-elem-anyelement-arr-anyarray"
             xreflabel="()">
      <title id="public.function.array-splice-from-elem-anyelement-arr-anyarray-title">
       array_splice_from(elem anyelement, arr anyarray)
      </title>
      <titleabbrev id="public.function.array-splice-from-elem-anyelement-arr-anyarray-titleabbrev">
       array_splice_from(elem anyelement, arr anyarray)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>anyarray</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    select $2[i:array_upper($2,1)]
      from generate_subscripts($2,1) as i
     where $2[i] = $1
     order by i
     limit 1;
  </programlisting>
      </para>
    </section>

<!-- Function array_splice_to(element anyelement, arr anyarray) -->
    <section id="public.function.array-splice-to-element-anyelement-arr-anyarray"
             xreflabel="()">
      <title id="public.function.array-splice-to-element-anyelement-arr-anyarray-title">
       array_splice_to(element anyelement, arr anyarray)
      </title>
      <titleabbrev id="public.function.array-splice-to-element-anyelement-arr-anyarray-titleabbrev">
       array_splice_to(element anyelement, arr anyarray)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>anyarray</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   select $2[1:i]
     from generate_subscripts($2,1) as i
    where $2[i] = $1
   order by i
   limit 1;
 </programlisting>
      </para>
    </section>

<!-- Function as_array(anyelement) -->
    <section id="public.function.as-array-anyelement"
             xreflabel="()">
      <title id="public.function.as-array-anyelement-title">
       as_array(anyelement)
      </title>
      <titleabbrev id="public.function.as-array-anyelement-titleabbrev">
       as_array(anyelement)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>INTERNAL</seg>
         <seg>anyarray</seg>
        </seglistitem>
       </segmentedlist>
 
        A basic array aggregate to take elements and return a one-dimensional array.

Example:  SELECT as_array(id) from entity_class;

        <programlisting>aggregate_dummy</programlisting>
      </para>
    </section>

<!-- Function assembly__stock(in_parts_id integer, in_qty numeric) -->
    <section id="public.function.assembly-stock-in-parts-id-integer-in-qty-numeric"
             xreflabel="()">
      <title id="public.function.assembly-stock-in-parts-id-integer-in-qty-numeric-title">
       assembly__stock(in_parts_id integer, in_qty numeric)
      </title>
      <titleabbrev id="public.function.assembly-stock-in-parts-id-integer-in-qty-numeric-titleabbrev">
       assembly__stock(in_parts_id integer, in_qty numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    INSERT INTO mfg_lot(parts_id, qty) VALUES ($1, $2);
    INSERT INTO mfg_lot_item(mfg_lot_id, parts_id, qty)
    SELECT currval(&#39;mfg_lot_id_seq&#39;)::int, parts_id, qty * $2
      FROM assembly WHERE id = $1;

    SELECT mfg_lot__commit(currval(&#39;mfg_lot_id_seq&#39;)::int);
</programlisting>
      </para>
    </section>

<!-- Function asset__get(in_id integer, in_tag text) -->
    <section id="public.function.asset-get-in-id-integer-in-tag-text"
             xreflabel="()">
      <title id="public.function.asset-get-in-id-integer-in-tag-text-title">
       asset__get(in_id integer, in_tag text)
      </title>
      <titleabbrev id="public.function.asset-get-in-id-integer-in-tag-text-titleabbrev">
       asset__get(in_id integer, in_tag text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves a given asset either by id or tag.  Both are complete matches.

Note that the behavior is undefined if both id and tag are provided.
        <programlisting>
        SELECT * from asset_item WHERE id = in_id OR in_tag = tag
        ORDER BY id desc limit 1;
</programlisting>
      </para>
    </section>

<!-- Function asset__import_from_disposal(in_id integer) -->
    <section id="public.function.asset-import-from-disposal-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-import-from-disposal-in-id-integer-title">
       asset__import_from_disposal(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-import-from-disposal-in-id-integer-titleabbrev">
       asset__import_from_disposal(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Imports items from partial disposal reports. This function should not be
called dirctly by programmers but rather through the other disposal approval
api&apos;s.
        <programlisting>
DECLARE t_report asset_report;
        t_import asset_report;
BEGIN

    SELECT * INTO t_report from asset_report where id = in_id;

    if t_report.report_class &lt;&gt; 4 THEN RETURN FALSE;
    END IF;

    SELECT *
      INTO t_import
      FROM  asset_report__begin_import
            (t_report.asset_class::int, t_report.report_date);

    PERFORM asset_report__import(
        ai.description,
        ai.tag,
        ai.purchase_value * rld.percent_disposed / 100,
        ai.salvage_value * rld.percent_disposed / 100,
        ai.usable_life,
        ai.purchase_date,
        ai.start_depreciation,
        ai.location_id,
        ai.department_id,
        ai.asset_account_id,
        ai.dep_account_id,
        ai.exp_account_id,
        ai.asset_class_id,
        ai.invoice_id,
        t_import.id,
        r.accum_depreciation * rld.percent_disposed / 100,
        TRUE)
    FROM asset_item ai
    JOIN asset_report__get_disposal(t_report.id) r  ON (ai.id = r.id)
    JOIN asset_report_line rl ON (rl.asset_id = ai.id AND rl.report_id = in_id)
    join asset_rl_to_disposal_method rld
         ON (rl.report_id = rld.report_id and ai.id = rld.asset_id)
   where rld.percent_disposed is null or percent_disposed &lt; 100;
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function asset__save(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer) -->
    <section id="public.function.asset-save-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer"
             xreflabel="()">
      <title id="public.function.asset-save-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer-title">
       asset__save(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer)
      </title>
      <titleabbrev id="public.function.asset-save-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer-titleabbrev">
       asset__save(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves the asset with the information provided.  If the id is provided,
overwrites the record with the id.  Otherwise, or if that record is not found,
inserts.  Returns the row inserted or updated.

        <programlisting>
DECLARE ret_val asset_item;
BEGIN
        UPDATE asset_item
        SET asset_class_id = in_asset_class,
                description = in_description,
                tag = in_tag,
                purchase_date = in_purchase_date,
                purchase_value = in_purchase_value,
                usable_life = in_usable_life,
                location_id = in_warehouse_id,
                department_id = in_department_id,
                invoice_id = in_invoice_id,
                salvage_value = in_salvage_value,
                asset_account_id = in_asset_account_id,
                exp_account_id = in_exp_account_id,
                start_depreciation =
                         coalesce(in_start_depreciation, in_purchase_date),
                dep_account_id = in_dep_account_id
        WHERE id = in_id;
        IF FOUND THEN
                SELECT * INTO ret_val FROM asset_item WHERE id = in_id;
                return ret_val;
        END IF;

        INSERT INTO asset_item (asset_class_id, description, tag, purchase_date,
                purchase_value, usable_life, salvage_value, department_id,
                location_id, invoice_id, asset_account_id, dep_account_id,
                start_depreciation, exp_account_id)
        VALUES (in_asset_class, in_description, in_tag, in_purchase_date,
                in_purchase_value, in_usable_life, in_salvage_value,
                in_department_id, in_warehouse_id, in_invoice_id,
                in_asset_account_id, in_dep_account_id,
                coalesce(in_start_depreciation, in_purchase_date),
                in_exp_account_id);

        SELECT * INTO ret_val FROM asset_item
        WHERE id = currval(&#39;asset_item_id_seq&#39;);
        RETURN ret_val;
END;
</programlisting>
      </para>
    </section>

<!-- Function asset__search(in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric) -->
    <section id="public.function.asset-search-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric"
             xreflabel="()">
      <title id="public.function.asset-search-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-title">
       asset__search(in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric)
      </title>
      <titleabbrev id="public.function.asset-search-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-titleabbrev">
       asset__search(in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_item</seg>
        </seglistitem>
       </segmentedlist>
 
       Searches for assets.  Nulls match all records.  Asset class is exact,
as is purchase date, purchase value, and salvage value. Tag and description
are partial matches.
        <programlisting>
                SELECT * FROM asset_item
                WHERE (in_asset_class is null
                        or asset_class_id = in_asset_class)
                        AND (in_description is null or description
                                LIKE &#39;%&#39; || in_description || &#39;%&#39;)
                        and (in_tag is null or tag like &#39;%&#39;||in_tag||&#39;%&#39;)
                        AND (in_purchase_date is null
                                or purchase_date = in_purchase_date)
                        AND (in_purchase_value is null
                                or in_purchase_value = purchase_value)
                        AND (in_usable_life is null
                                or in_usable_life = usable_life)
                        AND (in_salvage_value is null
                                OR in_salvage_value = salvage_value);
</programlisting>
      </para>
    </section>

<!-- Function asset_class__get(in_id integer) -->
    <section id="public.function.asset-class-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-class-get-in-id-integer-title">
       asset_class__get(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-class-get-in-id-integer-titleabbrev">
       asset_class__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_class</seg>
        </seglistitem>
       </segmentedlist>
 
        returns the row from asset_class identified by in_id.
        <programlisting>
        SELECT * FROM asset_class WHERE id = in_id;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__get_asset_accounts() -->
    <section id="public.function.asset-class-get-asset-accounts"
             xreflabel="()">
      <title id="public.function.asset-class-get-asset-accounts-title">
       asset_class__get_asset_accounts()
      </title>
      <titleabbrev id="public.function.asset-class-get-asset-accounts-titleabbrev">
       asset_class__get_asset_accounts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of fixed asset accounts, ordered by account number
        <programlisting>
SELECT * FROM account
WHERE id IN
        (select account_id from account_link where description = &#39;Fixed_Asset&#39;)
ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__get_dep_accounts() -->
    <section id="public.function.asset-class-get-dep-accounts"
             xreflabel="()">
      <title id="public.function.asset-class-get-dep-accounts-title">
       asset_class__get_dep_accounts()
      </title>
      <titleabbrev id="public.function.asset-class-get-dep-accounts-titleabbrev">
       asset_class__get_dep_accounts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of asset depreciation accounts, ordered by account number
        <programlisting>
SELECT * FROM account
WHERE id IN
        (select account_id from account_link where description = &#39;Asset_Dep&#39;)
ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__get_dep_method(in_asset_class integer) -->
    <section id="public.function.asset-class-get-dep-method-in-asset-class-integer"
             xreflabel="()">
      <title id="public.function.asset-class-get-dep-method-in-asset-class-integer-title">
       asset_class__get_dep_method(in_asset_class integer)
      </title>
      <titleabbrev id="public.function.asset-class-get-dep-method-in-asset-class-integer-titleabbrev">
       asset_class__get_dep_method(in_asset_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_dep_method</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns the depreciation method associated with the asset class.
        <programlisting>
SELECT * from asset_dep_method
WHERE id = (select method from asset_class where id = $1);
</programlisting>
      </para>
    </section>

<!-- Function asset_class__get_dep_methods() -->
    <section id="public.function.asset-class-get-dep-methods"
             xreflabel="()">
      <title id="public.function.asset-class-get-dep-methods-title">
       asset_class__get_dep_methods()
      </title>
      <titleabbrev id="public.function.asset-class-get-dep-methods-titleabbrev">
       asset_class__get_dep_methods()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_dep_method</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of asset_dep_methods ordered by the method label.
        <programlisting>
SELECT * FROM asset_dep_method ORDER BY method;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__list() -->
    <section id="public.function.asset-class-list"
             xreflabel="()">
      <title id="public.function.asset-class-list-title">
       asset_class__list()
      </title>
      <titleabbrev id="public.function.asset-class-list-titleabbrev">
       asset_class__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_class</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an alphabetical list of asset classes.
        <programlisting>
SELECT * FROM asset_class ORDER BY label;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__save(in_id integer, in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text, in_unit_label text) -->
    <section id="public.function.asset-class-save-in-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text-in-unit-label-text"
             xreflabel="()">
      <title id="public.function.asset-class-save-in-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text-in-unit-label-text-title">
       asset_class__save(in_id integer, in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text, in_unit_label text)
      </title>
      <titleabbrev id="public.function.asset-class-save-in-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text-in-unit-label-text-titleabbrev">
       asset_class__save(in_id integer, in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text, in_unit_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_class</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves this data as an asset_class record.  If in_id is NULL or is not found
in the table, inserts a new row.  Returns the row saved.
        <programlisting>
DECLARE ret_val asset_class;
BEGIN
        UPDATE asset_class
        SET asset_account_id = in_asset_account_id,
                dep_account_id = in_dep_account_id,
                method = in_method,
                label = in_label
        WHERE id = in_id;

        IF FOUND THEN
                SELECT * INTO ret_val FROM asset_class where id = in_id;
                RETURN ret_val;
        END IF;

        INSERT INTO asset_class (asset_account_id, dep_account_id, method,
                label)
        VALUES (in_asset_account_id, in_dep_account_id, in_method,
                in_label);

        SELECT * INTO ret_val FROM asset_class
        WHERE id = currval(&#39;asset_class_id_seq&#39;);

        RETURN ret_val;
END;
</programlisting>
      </para>
    </section>

<!-- Function asset_class__search(in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text) -->
    <section id="public.function.asset-class-search-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text"
             xreflabel="()">
      <title id="public.function.asset-class-search-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text-title">
       asset_class__search(in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text)
      </title>
      <titleabbrev id="public.function.asset-class-search-in-asset-account-id-integer-in-dep-account-id-integer-in-method-integer-in-label-text-titleabbrev">
       asset_class__search(in_asset_account_id integer, in_dep_account_id integer, in_method integer, in_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_class_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of matching asset classes.  The account id&apos;s are exact matches
as is the method, but the label is a partial match.  NULL&apos;s match all.
        <programlisting>
                SELECT ac.id, ac.asset_account_id, aa.accno, aa.description,
                        ac.dep_account_id, ad.accno, ad.description,
                        m.method, ac.method,
                        ac.label
                FROM asset_class ac
                JOIN account aa ON (aa.id = ac.asset_account_id)
                JOIN account ad ON (ad.id = ac.dep_account_id)
                JOIN asset_dep_method m ON (ac.method = m.id)
                WHERE
                        (in_asset_account_id is null
                                or in_asset_account_id = ac.asset_account_id)
                        AND (in_dep_account_id is null OR
                                in_dep_account_id = ac.dep_account_id)
                        AND (in_method is null OR in_method = ac.method)
                        AND (in_label IS NULL OR ac.label LIKE
                                &#39;%&#39; || in_label || &#39;%&#39;)
               ORDER BY label
</programlisting>
      </para>
    </section>

<!-- Function asset_dep__straight_line_base(in_base_life numeric, in_life numeric, in_used numeric, in_basis numeric, in_dep_to_date numeric) -->
    <section id="public.function.asset-dep-straight-line-base-in-base-life-numeric-in-life-numeric-in-used-numeric-in-basis-numeric-in-dep-to-date-numeric"
             xreflabel="()">
      <title id="public.function.asset-dep-straight-line-base-in-base-life-numeric-in-life-numeric-in-used-numeric-in-basis-numeric-in-dep-to-date-numeric-title">
       asset_dep__straight_line_base(in_base_life numeric, in_life numeric, in_used numeric, in_basis numeric, in_dep_to_date numeric)
      </title>
      <titleabbrev id="public.function.asset-dep-straight-line-base-in-base-life-numeric-in-life-numeric-in-used-numeric-in-basis-numeric-in-dep-to-date-numeric-titleabbrev">
       asset_dep__straight_line_base(in_base_life numeric, in_life numeric, in_used numeric, in_basis numeric, in_dep_to_date numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        This function is a basic function which does the actual calculation for
straight line depreciation.
        <programlisting>
SELECT CASE WHEN $3/$1 * $4 &lt; $4 - $5 THEN $3/$1 * $4
            ELSE $4 - $5
            END;
</programlisting>
      </para>
    </section>

<!-- Function asset_dep__used_months(in_last_dep date, in_dep_date date, in_usable_life numeric) -->
    <section id="public.function.asset-dep-used-months-in-last-dep-date-in-dep-date-date-in-usable-life-numeric"
             xreflabel="()">
      <title id="public.function.asset-dep-used-months-in-last-dep-date-in-dep-date-date-in-usable-life-numeric-title">
       asset_dep__used_months(in_last_dep date, in_dep_date date, in_usable_life numeric)
      </title>
      <titleabbrev id="public.function.asset-dep-used-months-in-last-dep-date-in-dep-date-date-in-usable-life-numeric-titleabbrev">
       asset_dep__used_months(in_last_dep date, in_dep_date date, in_usable_life numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        This checks the interval between the two dates, and if longer than the
usable life, returns the months in that interval.  Otherwise returns the
usable life.
        <programlisting>
select CASE WHEN extract(&#39;MONTHS&#39; FROM (date_trunc(&#39;day&#39;, $2) - date_trunc(&#39;day&#39;, $1)))
                 &gt; $3
            THEN $3
            ELSE extract(&#39;MONTHS&#39; FROM (date_trunc(&#39;day&#39;, $2) - date_trunc(&#39;day&#39;, $1)))::numeric
            END;
</programlisting>
      </para>
    </section>

<!-- Function asset_dep_get_usable_life_yr(in_usable_life numeric, in_start_date date, in_dep_date date) -->
    <section id="public.function.asset-dep-get-usable-life-yr-in-usable-life-numeric-in-start-date-date-in-dep-date-date"
             xreflabel="()">
      <title id="public.function.asset-dep-get-usable-life-yr-in-usable-life-numeric-in-start-date-date-in-dep-date-date-title">
       asset_dep_get_usable_life_yr(in_usable_life numeric, in_start_date date, in_dep_date date)
      </title>
      <titleabbrev id="public.function.asset-dep-get-usable-life-yr-in-usable-life-numeric-in-start-date-date-in-dep-date-date-titleabbrev">
       asset_dep_get_usable_life_yr(in_usable_life numeric, in_start_date date, in_dep_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       If the interval is less than 0 then 0.  If the interval is greater than the
usable life, then the usable life.  Otherwise, return the interval as a
fractional year.
        <programlisting>
   SELECT CASE WHEN $3 IS NULL or get_fractional_year($2, $3) &gt; $1
               then $1
               WHEN get_fractional_year($2, $3) &lt; 0
               THEN 0
               ELSE get_fractional_year($2, $3)
          END;
</programlisting>
      </para>
    </section>

<!-- Function asset_dep_straight_line_month(in_asset_ids integer[], in_report_date date, in_report_id integer) -->
    <section id="public.function.asset-dep-straight-line-month-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.asset-dep-straight-line-month-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-title">
       asset_dep_straight_line_month(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </title>
      <titleabbrev id="public.function.asset-dep-straight-line-month-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-titleabbrev">
       asset_dep_straight_line_month(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Performs straight line depreciation, selecting depreciation amounts, etc.
into a report for further review and approval.  Usable life is in months, and
depreciation is an equal amount every month.
        <programlisting>
     INSERT INTO asset_report_line (asset_id, report_id, amount, department_id,
                                   warehouse_id)
     SELECT ai.id, $3,
            asset_dep__straight_line_base(
                  ai.usable_life,
                  ai.usable_life --months
                  - months_passed(coalesce(start_depreciation, purchase_date),
                                  coalesce(max(report_date),
                                           start_depreciation,
                                           purchase_date)),
                  months_passed(coalesce(max(report_date),
                                         start_depreciation,
                                         purchase_date),
                                $2),
                  purchase_value - salvage_value,
                  coalesce(sum(l.amount), 0)),
            ai.department_id, ai.location_id
       FROM asset_item ai
  LEFT JOIN asset_report_line l ON (l.asset_id = ai.id)
  LEFT JOIN asset_report r ON (l.report_id = r.id)
      WHERE ai.id = ANY($1)
   GROUP BY ai.id, ai.start_depreciation, ai.purchase_date, ai.purchase_value,
            ai.salvage_value, ai.department_id, ai.location_id, ai.usable_life;

    UPDATE asset_report SET report_class = 1 WHERE id = $3;

    select true;
</programlisting>
      </para>
    </section>

<!-- Function asset_dep_straight_line_yr_d(in_asset_ids integer[], in_report_date date, in_report_id integer) -->
    <section id="public.function.asset-dep-straight-line-yr-d-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.asset-dep-straight-line-yr-d-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-title">
       asset_dep_straight_line_yr_d(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </title>
      <titleabbrev id="public.function.asset-dep-straight-line-yr-d-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-titleabbrev">
       asset_dep_straight_line_yr_d(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
     INSERT INTO asset_report_line (asset_id, report_id, amount, department_id,
                                   warehouse_id)
     SELECT ai.id, $3,
            asset_dep__straight_line_base(
                  ai.usable_life, -- years
                  ai.usable_life -
                  get_fractional_year(coalesce(max(report_date),
                                         start_depreciation,
                                         purchase_date),
                                       coalesce(start_depreciation,
                                         purchase_date)),
                  get_fractional_year(coalesce(max(report_date),
                                         start_depreciation,
                                         purchase_date),
                                $2),
                  purchase_value - salvage_value,
                  coalesce(sum(l.amount), 0)),
            ai.department_id, ai.location_id
       FROM asset_item ai
  LEFT JOIN asset_report_line l ON (l.asset_id = ai.id)
  LEFT JOIN asset_report r ON (l.report_id = r.id)
      WHERE ai.id = ANY($1)
   GROUP BY ai.id, ai.start_depreciation, ai.purchase_date, ai.purchase_value,
            ai.salvage_value, ai.department_id, ai.location_id, ai.usable_life;

    UPDATE asset_report SET report_class = 1 WHERE id = $3;

    select true;
</programlisting>
      </para>
    </section>

<!-- Function asset_dep_straight_line_yr_m(in_asset_ids integer[], in_report_date date, in_report_id integer) -->
    <section id="public.function.asset-dep-straight-line-yr-m-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.asset-dep-straight-line-yr-m-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-title">
       asset_dep_straight_line_yr_m(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </title>
      <titleabbrev id="public.function.asset-dep-straight-line-yr-m-in-asset-ids-integerARRAY-in-report-date-date-in-report-id-integer-titleabbrev">
       asset_dep_straight_line_yr_m(in_asset_ids integer[], in_report_date date, in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Performs straight line depreciation on a set of selected assets, selecting
the depreciation values into a report.

Assumes the usable life is measured in years, and is depreciated eavenly every
month.
        <programlisting>
     INSERT INTO asset_report_line (asset_id, report_id, amount, department_id,
                                   warehouse_id)
     SELECT ai.id, $3,
            asset_dep__straight_line_base(
                  ai.usable_life * 12,
                  ai.usable_life * 12 --months
                  - months_passed(coalesce(start_depreciation, purchase_date),
                                  coalesce(max(report_date),
                                           start_depreciation,
                                           purchase_date)),
                  months_passed(coalesce(max(report_date),
                                         start_depreciation,
                                         purchase_date),
                                $2),
                  purchase_value - salvage_value,
                  coalesce(sum(l.amount), 0)),
            ai.department_id, ai.location_id
       FROM asset_item ai
  LEFT JOIN asset_report_line l ON (l.asset_id = ai.id)
  LEFT JOIN asset_report r ON (l.report_id = r.id)
      WHERE ai.id = ANY($1)
   GROUP BY ai.id, ai.start_depreciation, ai.purchase_date, ai.purchase_value,
            ai.salvage_value, ai.department_id, ai.location_id, ai.usable_life;

    UPDATE asset_report SET report_class = 1 WHERE id = $3;

    select true;
</programlisting>
      </para>
    </section>

<!-- Function asset_depreciation__approve(in_report_id integer, in_expense_acct integer) -->
    <section id="public.function.asset-depreciation-approve-in-report-id-integer-in-expense-acct-integer"
             xreflabel="()">
      <title id="public.function.asset-depreciation-approve-in-report-id-integer-in-expense-acct-integer-title">
       asset_depreciation__approve(in_report_id integer, in_expense_acct integer)
      </title>
      <titleabbrev id="public.function.asset-depreciation-approve-in-report-id-integer-in-expense-acct-integer-titleabbrev">
       asset_depreciation__approve(in_report_id integer, in_expense_acct integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
       Approves an asset depreciation report and creats the GL draft.
        <programlisting>
declare retval asset_report;
begin

retval := asset_report__record_approve(in_report_id);

INSERT INTO gl (reference, description, approved)
select &#39;Asset Report &#39; || in_id, &#39;Asset Depreciation Report for &#39; || report_date,
       false
 FROM asset_report where id = in_id;

INSERT INTO acc_trans (amount, chart_id, transdate, approved, trans_id)
SELECT l.amount, a.dep_account_id, r.report_date, true, currval(&#39;id&#39;)
  FROM asset_report r
  JOIN asset_report_line l ON (r.id = l.report_id)
  JOIN asset_item a ON (a.id = l.asset_id)
 WHERE r.id = in_id;

INSERT INTO acc_trans (amount, chart_id, transdate, approved, trans_id)
SELECT sum(l.amount) * -1, in_expense_acct, r.report_date, approved,
       currval(&#39;id&#39;)
  FROM asset_report r
  JOIN asset_report_line l ON (r.id = l.report_id)
  JOIN asset_item a ON (a.id = l.asset_id)
 WHERE r.id = in_id
 GROUP BY r.report_date;


return retval;

end;
</programlisting>
      </para>
    </section>

<!-- Function asset_disposal__approve(in_id integer, in_gain_acct integer, in_loss_acct integer, in_asset_acct integer) -->
    <section id="public.function.asset-disposal-approve-in-id-integer-in-gain-acct-integer-in-loss-acct-integer-in-asset-acct-integer"
             xreflabel="()">
      <title id="public.function.asset-disposal-approve-in-id-integer-in-gain-acct-integer-in-loss-acct-integer-in-asset-acct-integer-title">
       asset_disposal__approve(in_id integer, in_gain_acct integer, in_loss_acct integer, in_asset_acct integer)
      </title>
      <titleabbrev id="public.function.asset-disposal-approve-in-id-integer-in-gain-acct-integer-in-loss-acct-integer-in-asset-acct-integer-titleabbrev">
       asset_disposal__approve(in_id integer, in_gain_acct integer, in_loss_acct integer, in_asset_acct integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
        This approves the asset_report for disposals, creating relevant GL drafts.

If the report is a partial disposal report, imports remaining percentages as new
asset items.
        <programlisting>
DECLARE
   retval asset_report;
   iter record;
   t_disposed_percent numeric;
begin
-- this code is fairly opaque and needs more documentation that would be
-- otherwise optimal. This is mostly due to the fact that we have fairly
-- repetitive insert/select routines and the fact that the accounting
-- requirements are not immediately intuitive.  Inserts marked functionally along
-- with typical debit/credit designations.  Note debits are always negative.


retval := asset_report__record_approve(in_id);
if retval.report_class = 2 then
     t_disposed_percent := 100;
end if;

INSERT INTO gl (reference, description, approved, transdate)
select &#39;Asset Report &#39; || in_id, &#39;Asset Disposal Report for &#39; || report_date,
       false, report_date
 FROM asset_report where id = in_id;

-- REMOVING ASSETS FROM ACCOUNT (Credit)
insert into acc_trans (trans_id, chart_id, amount, approved, transdate)
SELECT currval(&#39;id&#39;), a.asset_account_id,
       a.purchase_value
       * (coalesce(t_disposed_percent, m.percent_disposed)/100),
       true, r.report_date
 FROM  asset_item a
 JOIN  asset_report_line l ON (l.asset_id = a.id)
 JOIN  asset_report r ON (r.id = l.report_id)
 JOIN  asset_rl_to_disposal_method m
        ON (l.report_id = m.report_id and l.asset_id = m.asset_id)
 WHERE r.id = in_id;

-- REMOVING ACCUM DEP. (Debit)
INSERT into acc_trans (trans_id, chart_id, amount, approved, transdate)
SELECT currval(&#39;id&#39;), a.dep_account_id,
       sum(dl.amount) * -1
       * (coalesce(t_disposed_percent, m.percent_disposed)/100),
       true, r.report_date
 FROM  asset_item a
 JOIN  asset_report_line l ON (l.asset_id = a.id)
 JOIN  asset_report r ON (r.id = l.report_id)
 JOIN  asset_report_line dl ON (l.asset_id = dl.asset_id)
 JOIN  asset_rl_to_disposal_method m
        ON (l.report_id = m.report_id and l.asset_id = m.asset_id)
 JOIN  asset_report dr ON (dl.report_id = dr.id
                           and dr.report_class = 1
                           and dr.approved_at is not null)
 WHERE r.id = in_id
group by a.dep_account_id, m.percent_disposed, r.report_date;

-- INSERT asset/proceeds (Debit, credit for negative values)
INSERT INTO acc_trans (trans_id, chart_id, amount, approved, transdate)
SELECT currval(&#39;id&#39;), in_asset_acct, coalesce(l.amount, 0) * -1, true, r.report_date
 FROM  asset_item a
 JOIN  asset_report_line l ON (l.asset_id = a.id)
 JOIN  asset_report r ON (r.id = l.report_id)
 JOIN  asset_rl_to_disposal_method m
        ON (l.report_id = m.report_id and l.asset_id = m.asset_id)
 WHERE r.id = in_id;

-- INSERT GAIN/LOSS (Credit for gain, debit for loss)
INSERT INTO acc_trans(trans_id, chart_id, amount, approved, transdate)
select currval(&#39;id&#39;),
            CASE WHEN sum(amount) &gt; 0 THEN in_loss_acct
            else in_gain_acct
        END,
        sum(amount) * -1 , true,
        retval.report_date
  FROM acc_trans
  WHERE trans_id = currval(&#39;id&#39;);

IF retval.report_class = 4 then
   PERFORM asset__import_from_disposal(retval.id);
end if;

return retval;
end;
</programlisting>
      </para>
    </section>

<!-- Function asset_item__add_note(in_id integer, in_subject text, in_note text) -->
    <section id="public.function.asset-item-add-note-in-id-integer-in-subject-text-in-note-text"
             xreflabel="()">
      <title id="public.function.asset-item-add-note-in-id-integer-in-subject-text-in-note-text-title">
       asset_item__add_note(in_id integer, in_subject text, in_note text)
      </title>
      <titleabbrev id="public.function.asset-item-add-note-in-id-integer-in-subject-text-in-note-text-titleabbrev">
       asset_item__add_note(in_id integer, in_subject text, in_note text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Adds a note to an asset item
        <programlisting>
INSERT INTO asset_note (ref_key, subject, note) values ($1, $2, $3);
SELECT * FROM asset_note WHERE id = currval(&#39;note_id_seq&#39;);
</programlisting>
      </para>
    </section>

<!-- Function asset_item__search(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer) -->
    <section id="public.function.asset-item-search-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer"
             xreflabel="()">
      <title id="public.function.asset-item-search-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-title">
       asset_item__search(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer)
      </title>
      <titleabbrev id="public.function.asset-item-search-in-id-integer-in-asset-class-integer-in-description-text-in-tag-text-in-purchase-date-date-in-purchase-value-numeric-in-usable-life-numeric-in-salvage-value-numeric-in-start-depreciation-date-in-warehouse-id-integer-in-department-id-integer-in-invoice-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-titleabbrev">
       asset_item__search(in_id integer, in_asset_class integer, in_description text, in_tag text, in_purchase_date date, in_purchase_value numeric, in_usable_life numeric, in_salvage_value numeric, in_start_depreciation date, in_warehouse_id integer, in_department_id integer, in_invoice_id integer, in_asset_account_id integer, in_dep_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of matching asset items.  Nulls match all records.
Tag and description allow for partial match.  All other matches are exact.
        <programlisting>
         SELECT * FROM asset_item
          WHERE (id = in_id or in_id is null)
                and (asset_class_id = in_asset_class or in_asset_class is null)
                and (description like &#39;%&#39;||in_description||&#39;%&#39;
                     or in_description is null)
                and (tag like &#39;%&#39; || in_tag || &#39;%&#39; or in_tag is null)
                and (purchase_value = in_purchase_value
                    or in_purchase_value is null)
                and (in_purchase_date = purchase_date
                    or in_purchase_date is null)
                and (start_depreciation = in_start_depreciation
                    or in_start_depreciation is null)
                and (in_warehouse_id = location_id OR in_warehouse_id is null)
                and (department_id = in_department_id
                    or in_department_id is null)
                and (in_invoice_id = invoice_id OR in_invoice_id IS NULL)
                and (asset_account_id = in_asset_account_id
                    or in_asset_account_id is null)
                and (dep_account_id = in_dep_account_id
                    or in_dep_account_id is null);
</programlisting>
      </para>
    </section>

<!-- Function asset_nbv_report() -->
    <section id="public.function.asset-nbv-report"
             xreflabel="()">
      <title id="public.function.asset-nbv-report-title">
       asset_nbv_report()
      </title>
      <titleabbrev id="public.function.asset-nbv-report-titleabbrev">
       asset_nbv_report()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_nbv_line</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the current net book value report.
        <programlisting>
   SELECT ai.id, ai.tag, ai.description, coalesce(ai.start_depreciation, ai.purchase_date),
          adm.short_name, ai.usable_life
           - months_passed(coalesce(ai.start_depreciation, ai.purchase_date),
                                  coalesce(max(r.report_date),
                                           ai.start_depreciation,
                                           ai.purchase_date))/ 12,
          ai.purchase_value - ai.salvage_value, ai.salvage_value, max(r.report_date),
          sum(rl.amount), ai.purchase_value - coalesce(sum(rl.amount), 0)
     FROM asset_item ai
     JOIN asset_class ac ON (ai.asset_class_id = ac.id)
     JOIN asset_dep_method adm ON (adm.id = ac.method)
LEFT JOIN asset_report_line rl ON (ai.id = rl.asset_id)
LEFT JOIN asset_report r on (rl.report_id = r.id)
    WHERE r.id IS NULL OR r.approved_at IS NOT NULL
 GROUP BY ai.id, ai.tag, ai.description, ai.start_depreciation, ai.purchase_date,
          adm.short_name, ai.usable_life, ai.purchase_value, salvage_value
   HAVING (NOT 2 = ANY(as_array(r.report_class)))
          AND (NOT 4 = ANY(as_array(r.report_class)))
          OR max(r.report_class) IS NULL
 ORDER BY ai.id, ai.tag, ai.description;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__approve(in_id integer, in_expense_acct integer, in_gain_acct integer, in_loss_acct integer) -->
    <section id="public.function.asset-report-approve-in-id-integer-in-expense-acct-integer-in-gain-acct-integer-in-loss-acct-integer"
             xreflabel="()">
      <title id="public.function.asset-report-approve-in-id-integer-in-expense-acct-integer-in-gain-acct-integer-in-loss-acct-integer-title">
       asset_report__approve(in_id integer, in_expense_acct integer, in_gain_acct integer, in_loss_acct integer)
      </title>
      <titleabbrev id="public.function.asset-report-approve-in-id-integer-in-expense-acct-integer-in-gain-acct-integer-in-loss-acct-integer-titleabbrev">
       asset_report__approve(in_id integer, in_expense_acct integer, in_gain_acct integer, in_loss_acct integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
        This function approves an asset report (whether depreciation or disposal).
Also generates relevant GL drafts for review and posting.
        <programlisting>
DECLARE ret_val asset_report;
BEGIN
        UPDATE asset_report
           SET approved_at = now(),
               approved_by = person__get_my_entity_id()
         where id = in_id;
        SELECT * INTO ret_val FROM asset_report WHERE id = in_id;
        if ret_val.dont_approve is not true then
                if ret_val.report_class = 1 THEN
                    PERFORM asset_report__generate_gl(in_id, in_expense_acct);
                ELSIF ret_val.report_class = 2 THEN
                    PERFORM asset_report__disposal_gl(
                                 in_id, in_gain_acct, in_loss_acct);
                ELSIF ret_val.report_class = 4 THEN
                    PERFORM asset_disposal__approve(in_id, in_gain_acct, in_loss_acct, (select asset_account_id from asset_class
                                                                                         where id = ret_val.asset_class)
                                                   );
                ELSE RAISE EXCEPTION &#39;Invalid report class&#39;;
                END IF;
        end if;
        SELECT * INTO ret_val FROM asset_report WHERE id = in_id;
        RETURN ret_val;
end;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__begin_disposal(in_asset_class integer, in_report_date date, in_report_class integer) -->
    <section id="public.function.asset-report-begin-disposal-in-asset-class-integer-in-report-date-date-in-report-class-integer"
             xreflabel="()">
      <title id="public.function.asset-report-begin-disposal-in-asset-class-integer-in-report-date-date-in-report-class-integer-title">
       asset_report__begin_disposal(in_asset_class integer, in_report_date date, in_report_class integer)
      </title>
      <titleabbrev id="public.function.asset-report-begin-disposal-in-asset-class-integer-in-report-date-date-in-report-class-integer-titleabbrev">
       asset_report__begin_disposal(in_asset_class integer, in_report_date date, in_report_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
        Creates the asset report recofd for the asset disposal report.
        <programlisting>
DECLARE retval asset_report;

begin

INSERT INTO asset_report (asset_class, report_date, entered_at, entered_by,
            report_class)
     VALUES (in_asset_class, in_report_date, now(), person__get_my_entity_id(),
            in_report_class);

SELECT * INTO retval FROM asset_report where id = currval(&#39;asset_report_id_seq&#39;);

return retval;

end;

</programlisting>
      </para>
    </section>

<!-- Function asset_report__begin_import(in_asset_class integer, in_report_date date) -->
    <section id="public.function.asset-report-begin-import-in-asset-class-integer-in-report-date-date"
             xreflabel="()">
      <title id="public.function.asset-report-begin-import-in-asset-class-integer-in-report-date-date-title">
       asset_report__begin_import(in_asset_class integer, in_report_date date)
      </title>
      <titleabbrev id="public.function.asset-report-begin-import-in-asset-class-integer-in-report-date-date-titleabbrev">
       asset_report__begin_import(in_asset_class integer, in_report_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
       Creates the outline of an asset import report
        <programlisting>
INSERT INTO asset_report (asset_class, report_date, entered_at, entered_by,
            report_class, dont_approve)
     VALUES ($1, $2, now(), person__get_my_entity_id(),
            3, true);

SELECT * FROM asset_report where id = currval(&#39;asset_report_id_seq&#39;);

</programlisting>
      </para>
    </section>

<!-- Function asset_report__disposal_gl(in_id integer, in_gain_acct integer, in_loss_acct integer) -->
    <section id="public.function.asset-report-disposal-gl-in-id-integer-in-gain-acct-integer-in-loss-acct-integer"
             xreflabel="()">
      <title id="public.function.asset-report-disposal-gl-in-id-integer-in-gain-acct-integer-in-loss-acct-integer-title">
       asset_report__disposal_gl(in_id integer, in_gain_acct integer, in_loss_acct integer)
      </title>
      <titleabbrev id="public.function.asset-report-disposal-gl-in-id-integer-in-gain-acct-integer-in-loss-acct-integer-titleabbrev">
       asset_report__disposal_gl(in_id integer, in_gain_acct integer, in_loss_acct integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Generates GL transactions for ful disposal reports.
        <programlisting>
  INSERT
    INTO gl (reference, description, transdate, approved)
  SELECT setting_increment(&#39;glnumber&#39;), &#39;Asset Report &#39; || asset_report.id,
                report_date, false
    FROM asset_report
    JOIN asset_report_line ON (asset_report.id = asset_report_line.report_id)
    JOIN asset_item        ON (asset_report_line.asset_id = asset_item.id)
   WHERE asset_report.id = $1
GROUP BY asset_report.id, asset_report.report_date;

  INSERT
    INTO acc_trans (chart_id, trans_id, amount, approved, transdate)
  SELECT a.dep_account_id, currval(&#39;id&#39;)::int, sum(r.accum_depreciation) * -1,
         TRUE, r.disposed_on
    FROM asset_report__get_disposal($1) r
    JOIN asset_item a ON (r.id = a.id)
GROUP BY a.dep_account_id, r.disposed_on;

  -- GAIN is negative since it is a debit
  INSERT
    INTO acc_trans (chart_id, trans_id, amount, approved, transdate)
  SELECT case when sum(r.gain_loss) &gt; 0 THEN $3 else $2 end,
         currval(&#39;id&#39;)::int, sum(r.gain_loss),
         TRUE, r.disposed_on
    FROM asset_report__get_disposal($1) r
    JOIN asset_item ai ON (r.id = ai.id)
GROUP BY r.disposed_on;

  INSERT
    INTO acc_trans (chart_id, trans_id, amount, approved, transdate)
  SELECT a.asset_account_id, currval(&#39;id&#39;)::int, sum(r.purchase_value),
         TRUE, r.disposed_on
    FROM asset_report__get_disposal($1) r
    JOIN asset_item a ON (r.id = a.id)
GROUP BY a.asset_account_id, r.disposed_on;


  SELECT TRUE;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__dispose(in_id integer, in_asset_id integer, in_amount numeric, in_dm integer, in_percent_disposed numeric) -->
    <section id="public.function.asset-report-dispose-in-id-integer-in-asset-id-integer-in-amount-numeric-in-dm-integer-in-percent-disposed-numeric"
             xreflabel="()">
      <title id="public.function.asset-report-dispose-in-id-integer-in-asset-id-integer-in-amount-numeric-in-dm-integer-in-percent-disposed-numeric-title">
       asset_report__dispose(in_id integer, in_asset_id integer, in_amount numeric, in_dm integer, in_percent_disposed numeric)
      </title>
      <titleabbrev id="public.function.asset-report-dispose-in-id-integer-in-asset-id-integer-in-amount-numeric-in-dm-integer-in-percent-disposed-numeric-titleabbrev">
       asset_report__dispose(in_id integer, in_asset_id integer, in_amount numeric, in_dm integer, in_percent_disposed numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Disposes of an asset.  in_dm is the disposal method id.
        <programlisting>
BEGIN
    INSERT
      INTO asset_report_line (report_id, asset_id, amount)
    values (in_id, in_asset_id, in_amount);

    INSERT
      INTO asset_rl_to_disposal_method
           (report_id, asset_id, disposal_method_id, percent_disposed)
    VALUES (in_id, in_asset_id, in_dm, in_percent_disposed);

    RETURN TRUE;
    END;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__generate(in_depreciation boolean, in_asset_class integer, in_report_date date) -->
    <section id="public.function.asset-report-generate-in-depreciation-boolean-in-asset-class-integer-in-report-date-date"
             xreflabel="()">
      <title id="public.function.asset-report-generate-in-depreciation-boolean-in-asset-class-integer-in-report-date-date-title">
       asset_report__generate(in_depreciation boolean, in_asset_class integer, in_report_date date)
      </title>
      <titleabbrev id="public.function.asset-report-generate-in-depreciation-boolean-in-asset-class-integer-in-report-date-date-titleabbrev">
       asset_report__generate(in_depreciation boolean, in_asset_class integer, in_report_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Generates lines to select/deselect for the asset report (depreciation or
disposal).
        <programlisting>
   SELECT ai.*
     FROM asset_item ai
     JOIN asset_class ac ON (ai.asset_class_id = ac.id)
LEFT JOIN asset_report_line arl ON (arl.asset_id = ai.id)
LEFT JOIN asset_report ar ON (arl.report_id = ar.id)
    WHERE COALESCE(ai.start_depreciation, ai.purchase_date) &lt;= $3 AND ac.id = $2
          AND obsolete_by IS NULL
 GROUP BY ai.id, ai.tag, ai.description, ai.purchase_value, ai.usable_life,
          ai.purchase_date, ai.location_id, ai.invoice_id, ai.asset_account_id,
          ai.dep_account_id, ai.asset_class_id, ai.start_depreciation,
          ai.salvage_value, ai.department_id, ai.exp_account_id, ai.obsolete_by
   HAVING (count(ar.report_class) = 0 OR
          (2 &lt;&gt; ALL(as_array(ar.report_class))
          and 4 &lt;&gt; ALL(as_array(ar.report_class))))
          AND ((ai.purchase_value - coalesce(sum(arl.amount), 0)
               &gt; ai.salvage_value) and ai.obsolete_by is null)
               OR $1 is not true;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__generate_gl(in_report_id integer, in_accum_account_id integer) -->
    <section id="public.function.asset-report-generate-gl-in-report-id-integer-in-accum-account-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-generate-gl-in-report-id-integer-in-accum-account-id-integer-title">
       asset_report__generate_gl(in_report_id integer, in_accum_account_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-generate-gl-in-report-id-integer-in-accum-account-id-integer-titleabbrev">
       asset_report__generate_gl(in_report_id integer, in_accum_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Generates a GL transaction when the Asset report is approved.

Currently this creates GL drafts, not approved transctions

        <programlisting>
DECLARE
        t_report_dept record;
        t_dep_amount numeric;

Begin
        INSERT INTO gl (reference, description, transdate, approved)
        SELECT setting_increment(&#39;glnumber&#39;), &#39;Asset Report &#39; || asset_report.id,
                report_date, false
        FROM asset_report
        JOIN asset_report_line
                ON (asset_report.id = asset_report_line.report_id)
        JOIN asset_item
                ON (asset_report_line.asset_id = asset_item.id)
        WHERE asset_report.id = in_report_id
        GROUP BY asset_report.id, asset_report.report_date;

        INSERT INTO acc_trans (trans_id, chart_id, transdate, approved, amount)
        SELECT gl.id, a.exp_account_id, r.report_date, true, sum(amount) * -1
        FROM asset_report r
        JOIN asset_report_line l ON (r.id = l.report_id)
        JOIN asset_item a ON (l.asset_id = a.id)
        JOIN gl ON (gl.description = &#39;Asset Report &#39; || l.report_id)
        WHERE r.id = in_report_id
        GROUP BY gl.id, r.report_date, a.exp_account_id;

        INSERT INTO acc_trans (trans_id, chart_id, transdate, approved, amount)
        SELECT gl.id, a.dep_account_id, r.report_date, true, sum(amount)
        FROM asset_report r
        JOIN asset_report_line l ON (r.id = l.report_id)
        JOIN asset_item a ON (l.asset_id = a.id)
        JOIN gl ON (gl.description = &#39;Asset Report &#39; || l.report_id)
        WHERE r.id = in_report_id
        GROUP BY gl.id, a.dep_account_id, r.report_date, a.tag, a.description;

        RETURN in_report_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get(in_id integer) -->
    <section id="public.function.asset-report-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-get-in-id-integer-title">
       asset_report__get(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-get-in-id-integer-titleabbrev">
       asset_report__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the asset_report line identified by id.
        <programlisting>
select * from asset_report where id = $1;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_disposal(in_id integer) -->
    <section id="public.function.asset-report-get-disposal-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-get-disposal-in-id-integer-title">
       asset_report__get_disposal(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-get-disposal-in-id-integer-titleabbrev">
       asset_report__get_disposal(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_disposal_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of lines of disposed assets in a disposal report, specified
by the report id.
        <programlisting>
   SELECT ai.id, ai.tag, ai.description, ai.start_depreciation, r.report_date,
          dm.short_label, ai.purchase_value,
          sum (CASE WHEN pr.report_class in (1,3) THEN prl.amount ELSE 0 END)
          as accum_dep,
          l.amount,
          ai.purchase_value - sum(CASE WHEN pr.report_class in (1,3)
                                       THEN prl.amount
                                       ELSE 0
                                   END) as adjusted_basis,
          l.amount - ai.purchase_value + sum(CASE WHEN pr.report_class in (1,3)
                                                  THEN prl.amount
                                                  ELSE 0
                                              END) as gain_loss
     FROM asset_item ai
     JOIN asset_report_line l   ON (l.report_id = $1 AND ai.id = l.asset_id)
     JOIN asset_report r        ON (l.report_id = r.id)
LEFT JOIN asset_rl_to_disposal_method adm
                             USING (report_id, asset_id)
     JOIN asset_disposal_method dm
                                ON (adm.disposal_method_id = dm.id)
LEFT JOIN asset_report_line prl ON (prl.report_id &lt;&gt; $1
                                   AND ai.id = prl.asset_id)
LEFT JOIN asset_report pr       ON (prl.report_id = pr.id)
 GROUP BY ai.id, ai.tag, ai.description, ai.start_depreciation, r.report_date,
          ai.purchase_value, l.amount, dm.short_label
 ORDER BY ai.id, ai.tag;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_disposal_methods() -->
    <section id="public.function.asset-report-get-disposal-methods"
             xreflabel="()">
      <title id="public.function.asset-report-get-disposal-methods-title">
       asset_report__get_disposal_methods()
      </title>
      <titleabbrev id="public.function.asset-report-get-disposal-methods-titleabbrev">
       asset_report__get_disposal_methods()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_disposal_method</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of asset_disposal_method items ordered by label.
        <programlisting>
SELECT * FROM asset_disposal_method order by label;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_expense_accts() -->
    <section id="public.function.asset-report-get-expense-accts"
             xreflabel="()">
      <title id="public.function.asset-report-get-expense-accts-title">
       asset_report__get_expense_accts()
      </title>
      <titleabbrev id="public.function.asset-report-get-expense-accts-titleabbrev">
       asset_report__get_expense_accts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all asset expense reports.
        <programlisting>
    SELECT * FROM account__get_by_link_desc(&#39;asset_expense&#39;);
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_gain_accts() -->
    <section id="public.function.asset-report-get-gain-accts"
             xreflabel="()">
      <title id="public.function.asset-report-get-gain-accts-title">
       asset_report__get_gain_accts()
      </title>
      <titleabbrev id="public.function.asset-report-get-gain-accts-titleabbrev">
       asset_report__get_gain_accts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of gain accounts for asset depreciation and disposal reports.

        <programlisting>
    SELECT * FROM account__get_by_link_desc(&#39;asset_gain&#39;);
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_lines(in_id integer) -->
    <section id="public.function.asset-report-get-lines-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-get-lines-in-id-integer-title">
       asset_report__get_lines(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-get-lines-in-id-integer-titleabbrev">
       asset_report__get_lines(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_report_line_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the lines of an asset depreciation report.
        <programlisting>
   select ai.tag, coalesce(ai.start_depreciation, ai.purchase_date), ai.purchase_value, m.short_name,
          ai.usable_life,
          ai.purchase_value - ai.salvage_value, max(pr.report_date),
          sum(case when pr.report_date &lt; r.report_date then prl.amount
                   else 0
                end),
          rl.amount,
          sum (case when extract(year from pr.report_date)
                         = extract(year from r.report_date)
                         AND pr.report_date &lt; r.report_date
                    then prl.amount
                    else 0
                end),
          sum(prl.amount),
          ai.description, ai.purchase_date
     FROM asset_item ai
     JOIN asset_class c ON (ai.asset_class_id = c.id)
     JOIN asset_dep_method m ON (c.method = m.id)
     JOIN asset_report_line rl ON (rl.asset_id = ai.id)
     JOIN asset_report r ON (rl.report_id = r.id)
LEFT JOIN asset_report_line prl ON (prl.asset_id = ai.id)
LEFT JOIN asset_report pr ON (prl.report_id = pr.id)
    WHERE rl.report_id = $1
 GROUP BY ai.tag, ai.start_depreciation, ai.purchase_value, m.short_name,
          ai.usable_life, ai.salvage_value, r.report_date, rl.amount,
          ai.description, ai.purchase_date;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__get_loss_accts() -->
    <section id="public.function.asset-report-get-loss-accts"
             xreflabel="()">
      <title id="public.function.asset-report-get-loss-accts-title">
       asset_report__get_loss_accts()
      </title>
      <titleabbrev id="public.function.asset-report-get-loss-accts-titleabbrev">
       asset_report__get_loss_accts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of loss accounts for asset depreciation and disposal reports.

        <programlisting>
    SELECT * FROM account__get_by_link_desc(&#39;asset_loss&#39;);
</programlisting>
      </para>
    </section>

<!-- Function asset_report__import(in_description text, in_tag text, in_purchase_value numeric, in_salvage_value numeric, in_usable_life numeric, in_purchase_date date, in_start_depreciation date, in_location_id integer, in_department_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer, in_asset_class_id integer, in_invoice_id integer, in_dep_report_id integer, in_accum_dep numeric, in_obsolete_other boolean) -->
    <section id="public.function.asset-report-import-in-description-text-in-tag-text-in-purchase-value-numeric-in-salvage-value-numeric-in-usable-life-numeric-in-purchase-date-date-in-start-depreciation-date-in-location-id-integer-in-department-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer-in-asset-class-id-integer-in-invoice-id-integer-in-dep-report-id-integer-in-accum-dep-numeric-in-obsolete-other-boolean"
             xreflabel="()">
      <title id="public.function.asset-report-import-in-description-text-in-tag-text-in-purchase-value-numeric-in-salvage-value-numeric-in-usable-life-numeric-in-purchase-date-date-in-start-depreciation-date-in-location-id-integer-in-department-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer-in-asset-class-id-integer-in-invoice-id-integer-in-dep-report-id-integer-in-accum-dep-numeric-in-obsolete-other-boolean-title">
       asset_report__import(in_description text, in_tag text, in_purchase_value numeric, in_salvage_value numeric, in_usable_life numeric, in_purchase_date date, in_start_depreciation date, in_location_id integer, in_department_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer, in_asset_class_id integer, in_invoice_id integer, in_dep_report_id integer, in_accum_dep numeric, in_obsolete_other boolean)
      </title>
      <titleabbrev id="public.function.asset-report-import-in-description-text-in-tag-text-in-purchase-value-numeric-in-salvage-value-numeric-in-usable-life-numeric-in-purchase-date-date-in-start-depreciation-date-in-location-id-integer-in-department-id-integer-in-asset-account-id-integer-in-dep-account-id-integer-in-exp-account-id-integer-in-asset-class-id-integer-in-invoice-id-integer-in-dep-report-id-integer-in-accum-dep-numeric-in-obsolete-other-boolean-titleabbrev">
       asset_report__import(in_description text, in_tag text, in_purchase_value numeric, in_salvage_value numeric, in_usable_life numeric, in_purchase_date date, in_start_depreciation date, in_location_id integer, in_department_id integer, in_asset_account_id integer, in_dep_account_id integer, in_exp_account_id integer, in_asset_class_id integer, in_invoice_id integer, in_dep_report_id integer, in_accum_dep numeric, in_obsolete_other boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Imports an asset with the supplied information.  If in_obsolete_other is
false, this creates a new depreciable asset.  If it is true, it sets up the
other asset as obsolete.  This is the way partial disposal reports are handled.

        <programlisting>

SET CONSTRAINTS asset_item_obsolete_by_fkey DEFERRED;
-- This fails a deferrable fkey constraint but avoids a partial unique index
-- so in this case, the foreign key is deferred for the duration of this
-- specific stored proc call.

UPDATE asset_item
   SET obsolete_by = -1
 WHERE tag = $2 and $17 is true;

INSERT
  INTO asset_report_line
       (report_id, asset_id, amount, department_id, warehouse_id)
select $15, id, $16, department_id, location_id
  from asset__save
       (NULL, $13, $1, $2, $6, $3, $5, coalesce($4, 0), $7, $8, $9, $14, $10, $11, $12);

UPDATE asset_item
   SET obsolete_by = currval(&#39;asset_item_id_seq&#39;)
 WHERE obsolete_by = -1;

-- enforce fkeys now and raise exception if fail
SET CONSTRAINTS asset_item_obsolete_by_fkey IMMEDIATE;
SELECT true;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__record_approve(in_id integer) -->
    <section id="public.function.asset-report-record-approve-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-record-approve-in-id-integer-title">
       asset_report__record_approve(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-record-approve-in-id-integer-titleabbrev">
       asset_report__record_approve(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
       Marks the asset_report record approved.  Not generally recommended to call
directly.
        <programlisting>
UPDATE asset_report
   set approved_by = person__get_my_entity_id(),
       approved_at = now()
 where id = $1;

select * from asset_report where id = $1;

</programlisting>
      </para>
    </section>

<!-- Function asset_report__save(in_id integer, in_report_date date, in_report_class integer, in_asset_class integer, in_submit boolean) -->
    <section id="public.function.asset-report-save-in-id-integer-in-report-date-date-in-report-class-integer-in-asset-class-integer-in-submit-boolean"
             xreflabel="()">
      <title id="public.function.asset-report-save-in-id-integer-in-report-date-date-in-report-class-integer-in-asset-class-integer-in-submit-boolean-title">
       asset_report__save(in_id integer, in_report_date date, in_report_class integer, in_asset_class integer, in_submit boolean)
      </title>
      <titleabbrev id="public.function.asset-report-save-in-id-integer-in-report-date-date-in-report-class-integer-in-asset-class-integer-in-submit-boolean-titleabbrev">
       asset_report__save(in_id integer, in_report_date date, in_report_class integer, in_asset_class integer, in_submit boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>asset_report</seg>
        </seglistitem>
       </segmentedlist>
 
        Creates or updates an asset report with the information presented.  Note that
approval values are not set here, and that one cannot unsubmit a report though
this function.
        <programlisting>
DECLARE
        ret_val asset_report;
        item record;
        method_text text;
BEGIN
        UPDATE asset_report
        set asset_class = in_asset_class,
                report_class = in_report_class,
                report_date = in_report_date,
                submitted = (in_submit or submitted)
        WHERE id = in_id;

        IF FOUND THEN
                SELECT * INTO ret_val FROM asset_report WHERE id = in_id;
        ELSE
                INSERT INTO asset_report(report_class, asset_class, report_date,
                        submitted)
                values (in_report_class, in_asset_class, in_report_date,
                        coalesce(in_submit, true));

                SELECT * INTO ret_val FROM asset_report
                WHERE id = currval(&#39;asset_report_id_seq&#39;);

        END IF;
        RETURN ret_val;

END;
</programlisting>
      </para>
    </section>

<!-- Function asset_report__search(in_start_date date, in_end_date date, in_asset_class integer, in_approved boolean, in_entered_by integer) -->
    <section id="public.function.asset-report-search-in-start-date-date-in-end-date-date-in-asset-class-integer-in-approved-boolean-in-entered-by-integer"
             xreflabel="()">
      <title id="public.function.asset-report-search-in-start-date-date-in-end-date-date-in-asset-class-integer-in-approved-boolean-in-entered-by-integer-title">
       asset_report__search(in_start_date date, in_end_date date, in_asset_class integer, in_approved boolean, in_entered_by integer)
      </title>
      <titleabbrev id="public.function.asset-report-search-in-start-date-date-in-end-date-date-in-asset-class-integer-in-approved-boolean-in-entered-by-integer-titleabbrev">
       asset_report__search(in_start_date date, in_end_date date, in_asset_class integer, in_approved boolean, in_entered_by integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF asset_report_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Searches for asset reports.  Nulls match all rows.  Approved, asset class,
and entered_by are exact matches.  Start_date and end_date define the beginning
and end of the search date. 
        <programlisting>

  SELECT r.id, r.report_date, r.gl_id, r.asset_class, r.report_class,
         r.entered_by, r.approved_by, r.entered_at, r.approved_at,
         r.depreciated_qty, r.dont_approve, r.submitted, sum(l.amount)
    FROM asset_report r
    JOIN asset_report_line l ON (l.report_id = r.id)
   where ($1 is null or $1 &lt;= report_date)
         and ($2 is null or $2 &gt;= report_date)
         and ($3 is null or $3 = asset_class)
         and ($4 is null
              or ($4 is true and approved_by is not null)
              or ($4 is false and approved_by is null))
         and ($5 is null or $5 = entered_by)
GROUP BY r.id, r.report_date, r.gl_id, r.asset_class, r.report_class,
         r.entered_by, r.approved_by, r.entered_at, r.approved_at,
         r.depreciated_qty, r.dont_approve, r.submitted;
</programlisting>
      </para>
    </section>

<!-- Function asset_report_partial_disposal_details(in_id integer) -->
    <section id="public.function.asset-report-partial-disposal-details-in-id-integer"
             xreflabel="()">
      <title id="public.function.asset-report-partial-disposal-details-in-id-integer-title">
       asset_report_partial_disposal_details(in_id integer)
      </title>
      <titleabbrev id="public.function.asset-report-partial-disposal-details-in-id-integer-titleabbrev">
       asset_report_partial_disposal_details(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF partial_disposal_line</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the partial disposal details for a partial disposal report.
        <programlisting>
SELECT ai.id, ai.tag, ai.start_depreciation, ai.purchase_value, ai.description,
       ar.report_date, arld.percent_disposed,
       (arld.percent_disposed / 100) * ai.purchase_value,
       100 - arld.percent_disposed,
       ((100 - arld.percent_disposed)/100) * ai.purchase_value
  FROM asset_item ai
  JOIN asset_report_line l ON (ai.id = l.asset_id)
  JOIN asset_report ar ON (ar.id = l.report_id)
  JOIN asset_rl_to_disposal_method arld
       ON  ((arld.report_id, arld.asset_id) = (l.report_id, l.asset_id))
 WHERE ar.id = $1;
</programlisting>
      </para>
    </section>

<!-- Function avgcost(integer) -->
    <section id="public.function.avgcost-integer"
             xreflabel="()">
      <title id="public.function.avgcost-integer-title">
       avgcost(integer)
      </title>
      <titleabbrev id="public.function.avgcost-integer-titleabbrev">
       avgcost(integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>double precision</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

DECLARE

v_cost float;
v_qty float;
v_parts_id alias for $1;

BEGIN

  SELECT INTO v_cost, v_qty SUM(i.sellprice * i.qty), SUM(i.qty)
  FROM invoice i
  JOIN ap a ON (a.id = i.trans_id)
  WHERE i.parts_id = v_parts_id;

  IF v_cost IS NULL THEN
    v_cost := 0;
  END IF;

  IF NOT v_qty IS NULL THEN
    IF v_qty = 0 THEN
      v_cost := 0;
    ELSE
      v_cost := v_cost/v_qty;
    END IF;
  END IF;

RETURN v_cost;
END;
</programlisting>
      </para>
    </section>

<!-- Function batch__lock(in_batch_id integer) -->
    <section id="public.function.batch-lock-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.batch-lock-in-batch-id-integer-title">
       batch__lock(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.batch-lock-in-batch-id-integer-titleabbrev">
       batch__lock(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
UPDATE batch SET locked_by = (select max(session_id)
                                FROM &quot;session&quot; where users_id = (
                                        select id from users
                                         WHERE username = SESSION_USER))
 WHERE locked_by IS NULL
RETURNING true;
</programlisting>
      </para>
    </section>

<!-- Function batch__lock_for_update(in_batch_id integer) -->
    <section id="public.function.batch-lock-for-update-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.batch-lock-for-update-in-batch-id-integer-title">
       batch__lock_for_update(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.batch-lock-for-update-in-batch-id-integer-titleabbrev">
       batch__lock_for_update(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>batch</seg>
        </seglistitem>
       </segmentedlist>
 
        Locks a batch for the duration of the running transaction.
To be used when adding vouchers to the batch to prevent others
from hitting the batch for other purposes (e.g. approval) 
        <programlisting>
SELECT * FROM batch WHERE id = $1 FOR UPDATE;
</programlisting>
      </para>
    </section>

<!-- Function batch__search(in_class_id integer, in_description text, in_created_by_eid integer, in_date_from date, in_date_to date, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean) -->
    <section id="public.function.batch-search-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-date-from-date-in-date-to-date-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.batch-search-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-date-from-date-in-date-to-date-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean-title">
       batch__search(in_class_id integer, in_description text, in_created_by_eid integer, in_date_from date, in_date_to date, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean)
      </title>
      <titleabbrev id="public.function.batch-search-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-date-from-date-in-date-to-date-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean-titleabbrev">
       batch__search(in_class_id integer, in_description text, in_created_by_eid integer, in_date_from date, in_date_to date, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF batch_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a list of batches and amounts processed on the batch.

Nulls match all values.
in_date_from and in_date_to specify date ranges.
in_description is a partial match.
All other criteria are exact matches.

        <programlisting>
                SELECT b.id, c.class, b.control_code, b.description, u.username,
                        b.created_on, b.default_date,
                        sum(
                                CASE WHEN vc.id = 5 AND al.amount &lt; 0 -- GL
                                     THEN al.amount
                                     WHEN vc.id  = 1
                                     THEN ap.amount
                                     WHEN vc.id = 2
                                     THEN ar.amount
                                     ELSE 0
                                END) AS transaction_total,
                        sum(
                                CASE WHEN alc.link = &#39;AR&#39; AND vc.id IN (6, 7)
                                     THEN al.amount
                                     WHEN alc.link = &#39;AP&#39; AND vc.id IN (3, 4)
                                     THEN al.amount * -1
                                     ELSE 0
                                END
                           ) AS payment_total,
                     batch__lock(b.id)
                FROM batch b
                JOIN batch_class c ON (b.batch_class_id = c.id)
                LEFT JOIN users u ON (u.entity_id = b.created_by)
                LEFT JOIN voucher v ON (v.batch_id = b.id)
                LEFT JOIN batch_class vc ON (v.batch_class = vc.id)
                LEFT JOIN ar ON (vc.id = 2 AND v.trans_id = ar.id)
                LEFT JOIN ap ON (vc.id = 1 AND v.trans_id = ap.id)
                LEFT JOIN acc_trans al ON
                        ((vc.id = 5 AND v.trans_id = al.trans_id) OR
                                (vc.id IN (3, 4, 6, 7)
                                        AND al.voucher_id = v.id))
                LEFT JOIN chart alc ON (al.chart_id = alc.id)
                WHERE (c.id = in_class_id OR in_class_id IS NULL) AND
                        (b.description LIKE
                                &#39;%&#39; || in_description || &#39;%&#39; OR
                                in_description IS NULL) AND
                        (in_created_by_eid = b.created_by OR
                                in_created_by_eid IS NULL) AND
                        (((in_approved = false OR in_approved IS NULL)
                          AND approved_on IS NULL)
                         OR (in_approved = true AND approved_on IS NOT NULL))
                        and (in_date_from IS NULL
                                or b.default_date &gt;= in_date_from)
                        and (in_date_to IS NULL
                                or b.default_date &lt;= in_date_to)
                GROUP BY b.id, c.class, b.description, u.username, b.created_on,
                        b.control_code, b.default_date
                HAVING
                        (in_amount_gt IS NULL OR
                        sum(coalesce(ar.amount - ar.paid, ap.amount - ap.paid,
                                al.amount))
                        &gt;= in_amount_gt)
                        AND
                        (in_amount_lt IS NULL OR
                        sum(coalesce(ar.amount - ar.paid, ap.amount - ap.paid,
                                al.amount))
                        &lt;= in_amount_lt)
                ORDER BY b.control_code, b.description

</programlisting>
      </para>
    </section>

<!-- Function batch__unlock(in_batch_id integer) -->
    <section id="public.function.batch-unlock-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.batch-unlock-in-batch-id-integer-title">
       batch__unlock(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.batch-unlock-in-batch-id-integer-titleabbrev">
       batch__unlock(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
UPDATE batch SET locked_by = NULL
 WHERE id = $1 AND locked_by IN (select session_id
                                   from &quot;session&quot; s
                                   join users u on (u.id = s.users_id)
                                  where username = SESSION_USER)
RETURNING true;
</programlisting>
      </para>
    </section>

<!-- Function batch_create(in_batch_number text, in_description text, in_batch_class text, in_batch_date date) -->
    <section id="public.function.batch-create-in-batch-number-text-in-description-text-in-batch-class-text-in-batch-date-date"
             xreflabel="()">
      <title id="public.function.batch-create-in-batch-number-text-in-description-text-in-batch-class-text-in-batch-date-date-title">
       batch_create(in_batch_number text, in_description text, in_batch_class text, in_batch_date date)
      </title>
      <titleabbrev id="public.function.batch-create-in-batch-number-text-in-description-text-in-batch-class-text-in-batch-date-date-titleabbrev">
       batch_create(in_batch_number text, in_description text, in_batch_class text, in_batch_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Inserts the batch into the table.
        <programlisting>
        INSERT INTO
                batch (batch_class_id, default_date, description, control_code,
                        created_by)
        VALUES ((SELECT id FROM batch_class WHERE class = in_batch_class),
                in_batch_date, in_description, in_batch_number,
                        (select entity_id FROM users WHERE username = session_user))
        RETURNING id;

</programlisting>
      </para>
    </section>

<!-- Function batch_delete(in_batch_id integer) -->
    <section id="public.function.batch-delete-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.batch-delete-in-batch-id-integer-title">
       batch_delete(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.batch-delete-in-batch-id-integer-titleabbrev">
       batch_delete(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        If the batch is found and unapproved, deletes it and returns 1.
Otherwise raises an exception.
        <programlisting>
DECLARE
        t_transaction_ids int[];
BEGIN
        -- Adjust AR/AP tables for payment and payment reversal vouchers
        -- voucher_id is only set in acc_trans on payment/receipt vouchers and
        -- their reversals. -CT
        perform * from batch where id = in_batch_id and approved_on IS NULL;
        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;Batch not found&#39;;
        END IF;
        update ar set paid = amount +
                (select sum(amount) from acc_trans
                join chart ON (acc_trans.chart_id = chart.id)
                where link = &#39;AR&#39; AND trans_id = ar.id
                        AND (voucher_id IS NULL OR voucher_id NOT IN
                                (select id from voucher
                                WHERE batch_id = in_batch_id)))
        where id in (select trans_id from acc_trans where voucher_id IN
                (select id from voucher where batch_id = in_batch_id));

        update ap set paid = amount - (select sum(amount) from acc_trans
                join chart ON (acc_trans.chart_id = chart.id)
                where link = &#39;AP&#39; AND trans_id = ap.id
                        AND (voucher_id IS NULL OR voucher_id NOT IN
                                (select id from voucher
                                WHERE batch_id = in_batch_id)))
        where id in (select trans_id from acc_trans where voucher_id IN
                (select id from voucher where batch_id = in_batch_id));

        DELETE FROM ac_tax_form WHERE entry_id IN
               (select entry_id from acc_trans where voucher_id in
                       (select id from voucher where batch_id = in_batch_id)
               );

        DELETE FROM acc_trans WHERE voucher_id IN
                (select id FROM voucher where batch_id = in_batch_id);

        -- The rest of this function involves the deletion of actual
        -- transactions, vouchers, and batches, and jobs which are in progress.
        -- -CT
        SELECT as_array(trans_id) INTO t_transaction_ids
        FROM voucher WHERE batch_id = in_batch_id AND batch_class IN (1, 2, 5, 8, 9);

        DELETE FROM ac_tax_form WHERE entry_id in
               (select entry_id from acc_trans
                 where trans_id = any(t_transaction_ids));
        DELETE FROM invoice_tax_form WHERE invoice_id in
               (select id from invoice
                 where trans_id = any(t_transaction_ids));

        DELETE FROM invoice WHERE trans_id = ANY(t_transaction_ids);
        DELETE FROM acc_trans WHERE trans_id = ANY(t_transaction_ids);
        DELETE FROM ar WHERE id = ANY(t_transaction_ids);
        DELETE FROM ap WHERE id = ANY(t_transaction_ids);
        DELETE FROM gl WHERE id = ANY(t_transaction_ids);
        DELETE FROM voucher WHERE batch_id = in_batch_id;
        DELETE FROM batch WHERE id = in_batch_id;
        DELETE FROM transactions WHERE id = ANY(t_transaction_ids);

        RETURN 1;
END;
</programlisting>
      </para>
    </section>

<!-- Function batch_get_class_id(in_type text) -->
    <section id="public.function.batch-get-class-id-in-type-text"
             xreflabel="()">
      <title id="public.function.batch-get-class-id-in-type-text-title">
       batch_get_class_id(in_type text)
      </title>
      <titleabbrev id="public.function.batch-get-class-id-in-type-text-titleabbrev">
       batch_get_class_id(in_type text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        returns the batch class id associated with the in_type label provided.
        <programlisting>
SELECT id FROM batch_class WHERE class = $1;
</programlisting>
      </para>
    </section>

<!-- Function batch_get_users() -->
    <section id="public.function.batch-get-users"
             xreflabel="()">
      <title id="public.function.batch-get-users-title">
       batch_get_users()
      </title>
      <titleabbrev id="public.function.batch-get-users-titleabbrev">
       batch_get_users()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF users</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a sim[ple set of user objects.  This should be renamed so that
it is more obvious it is a general purpose function.
        <programlisting>
                SELECT * from users WHERE entity_id IN (select created_by from batch)
</programlisting>
      </para>
    </section>

<!-- Function batch_list_classes() -->
    <section id="public.function.batch-list-classes"
             xreflabel="()">
      <title id="public.function.batch-list-classes-title">
       batch_list_classes()
      </title>
      <titleabbrev id="public.function.batch-list-classes-titleabbrev">
       batch_list_classes()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF batch_class</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of all batch classes.
        <programlisting>
DECLARE out_val record;
BEGIN
        FOR out_val IN select * from batch_class order by id
        LOOP
                return next out_val;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function batch_post(in_batch_id integer) -->
    <section id="public.function.batch-post-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.batch-post-in-batch-id-integer-title">
       batch_post(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.batch-post-in-batch-id-integer-titleabbrev">
       batch_post(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>date</seg>
        </seglistitem>
       </segmentedlist>
 
        Posts the specified batch to the books.  Only posted batches should show up
on standard financial reports.
        <programlisting>
        UPDATE ar SET approved = true
        WHERE id IN (select trans_id FROM voucher
                WHERE batch_id = in_batch_id
                AND batch_class = 2);

        UPDATE ap SET approved = true
        WHERE id IN (select trans_id FROM voucher
                WHERE batch_id = in_batch_id
                AND batch_class = 1);

        UPDATE gl SET approved = true
        WHERE id IN (select trans_id FROM voucher
                WHERE batch_id = in_batch_id
                AND batch_class = 5);

        UPDATE acc_trans SET approved = true
        WHERE voucher_id IN (select id FROM voucher
                WHERE batch_id = in_batch_id
                AND batch_class IN (3, 4, 6, 7));

        UPDATE batch
        SET approved_on = now(),
                approved_by = (select entity_id FROM users
                        WHERE username = SESSION_USER)
        WHERE id = in_batch_id;

        SELECT now()::date;
</programlisting>
      </para>
    </section>

<!-- Function batch_search_empty(in_class_id integer, in_description text, in_created_by_eid integer, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean) -->
    <section id="public.function.batch-search-empty-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.batch-search-empty-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean-title">
       batch_search_empty(in_class_id integer, in_description text, in_created_by_eid integer, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean)
      </title>
      <titleabbrev id="public.function.batch-search-empty-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-amount-gt-numeric-in-amount-lt-numeric-in-approved-boolean-titleabbrev">
       batch_search_empty(in_class_id integer, in_description text, in_created_by_eid integer, in_amount_gt numeric, in_amount_lt numeric, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF batch_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This is a full search for the batches, listing them by amount processed.
in_amount_gt and in_amount_lt provide a range to search for.
in_description is a partial match field.
Other fields are exact matches.

NULLs match all values.

        <programlisting>
               SELECT b.id, c.class, b.control_code, b.description, u.username,
                        b.created_on, b.default_date, 0::numeric, 0::numeric, false
                FROM batch b
                JOIN batch_class c ON (b.batch_class_id = c.id)
                JOIN users u ON (u.entity_id = b.created_by)
                LEFT JOIN voucher v ON (v.batch_id = b.id)
               where v.id is null
                     and(u.entity_id = in_created_by_eid
                     or in_created_by_eid is null) and
                     (in_description is null or b.description
                     like &#39;%&#39;  || in_description || &#39;%&#39;) and
                     (in_class_id is null or c.id = in_class_id)
            GROUP BY b.id, c.class, b.description, u.username, b.created_on,
                     b.control_code, b.default_date
            ORDER BY b.control_code, b.description


</programlisting>
      </para>
    </section>

<!-- Function batch_search_mini(in_class_id integer, in_description text, in_created_by_eid integer, in_approved boolean) -->
    <section id="public.function.batch-search-mini-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.batch-search-mini-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-approved-boolean-title">
       batch_search_mini(in_class_id integer, in_description text, in_created_by_eid integer, in_approved boolean)
      </title>
      <titleabbrev id="public.function.batch-search-mini-in-class-id-integer-in-description-text-in-created-by-eid-integer-in-approved-boolean-titleabbrev">
       batch_search_mini(in_class_id integer, in_description text, in_created_by_eid integer, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF batch_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This performs a simple search of open batches created by the entity_id
in question.  This is used to pull up batches that were currently used so that
they can be picked up and more vouchers added.

NULLs match all values.
in_description is a partial match
All other inouts are exact matches.

        <programlisting>
                SELECT b.id, c.class, b.control_code, b.description, u.username,
                        b.created_on, b.default_date, NULL::NUMERIC, NULL::numeric, false
                FROM batch b
                JOIN batch_class c ON (b.batch_class_id = c.id)
                LEFT JOIN users u ON (u.entity_id = b.created_by)
                WHERE (c.id = in_class_id OR in_class_id IS NULL) AND
                        (b.description LIKE
                                &#39;%&#39; || in_description || &#39;%&#39; OR
                                in_description IS NULL) AND
                        (in_created_by_eid = b.created_by OR
                                in_created_by_eid IS NULL) AND
                        ((in_approved = false OR in_approved IS NULL AND
                                approved_on IS NULL) OR
                                (in_approved = true AND approved_on IS NOT NULL)
                        )
                GROUP BY b.id, c.class, b.description, u.username, b.created_on,
                        b.control_code, b.default_date
</programlisting>
      </para>
    </section>

<!-- Function budget__approve(in_id integer) -->
    <section id="public.function.budget-approve-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-approve-in-id-integer-title">
       budget__approve(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-approve-in-id-integer-titleabbrev">
       budget__approve(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
UPDATE budget_info
   set approved_at = now(), approved_by = person__get_my_entity_id()
 WHERE id = $1;

SELECT budget__get_info($1);
</programlisting>
      </para>
    </section>

<!-- Function budget__get_business_units(in_id integer) -->
    <section id="public.function.budget-get-business-units-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-get-business-units-in-id-integer-title">
       budget__get_business_units(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-get-business-units-in-id-integer-titleabbrev">
       budget__get_business_units(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF business_unit</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> select bu.*
     FROM business_unit bu
     JOIN budget_to_business_unit b2bu ON b2bu.bu_id = bu.id
     JOIN budget_info bi ON bi.id = b2bu.budget_id
    WHERE bi.id = $1
 ORDER BY bu.class_id;
</programlisting>
      </para>
    </section>

<!-- Function budget__get_details(in_id integer) -->
    <section id="public.function.budget-get-details-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-get-details-in-id-integer-title">
       budget__get_details(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-get-details-in-id-integer-titleabbrev">
       budget__get_details(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF budget_line_details</seg>
        </seglistitem>
       </segmentedlist>
 
        This retrieves the budget lines associated with a budget.
        <programlisting>
  SELECT l.budget_id, l.account_id, l.description, l.amount,
         a.accno, a.description,
         CASE WHEN l.amount &lt; 0 THEN l.amount * -1 ELSE NULL END,
         CASE WHEN l.amount &gt; 0 THEN l.amount ELSE NULL END
    FROM budget_line l
    JOIN account a ON a.id = l.account_id
   where budget_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function budget__get_info(in_id integer) -->
    <section id="public.function.budget-get-info-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-get-info-in-id-integer-title">
       budget__get_info(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-get-info-in-id-integer-titleabbrev">
       budget__get_info(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
        Selects the budget info. 
        <programlisting>
select bi.id, bi.start_date, bi.end_date, bi.reference, bi.description,
       bi.entered_by, bi.approved_by, bi.obsolete_by, bi.entered_at,
       bi.approved_at, bi.obsolete_at,
       ee.name, ae.name, oe.name
  from budget_info bi
  JOIN entity ee ON bi.entered_by = ee.id
  LEFT JOIN entity ae ON bi.approved_by = ae.id
  LEFT JOIN entity oe ON bi.obsolete_by = oe.id
 where bi.id = $1;
</programlisting>
      </para>
    </section>

<!-- Function budget__get_notes(in_id integer) -->
    <section id="public.function.budget-get-notes-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-get-notes-in-id-integer-title">
       budget__get_notes(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-get-notes-in-id-integer-titleabbrev">
       budget__get_notes(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF budget_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns all notes associated with a budget, by default in the order they
were created.
        <programlisting>
SELECT * FROM budget_note WHERE ref_key = $1
 ORDER BY created;
</programlisting>
      </para>
    </section>

<!-- Function budget__mark_obsolete(in_id integer) -->
    <section id="public.function.budget-mark-obsolete-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-mark-obsolete-in-id-integer-title">
       budget__mark_obsolete(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-mark-obsolete-in-id-integer-titleabbrev">
       budget__mark_obsolete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
        Marks a budget as obsolete 
        <programlisting>
UPDATE budget_info
   set obsolete_by = person__get_my_entity_id(), obsolete_at = now()
 WHERE id = $1 and approved_by is not null;
SELECT budget__get_info($1)
</programlisting>
      </para>
    </section>

<!-- Function budget__reject(in_id integer) -->
    <section id="public.function.budget-reject-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-reject-in-id-integer-title">
       budget__reject(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-reject-in-id-integer-titleabbrev">
       budget__reject(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes unapproved budgets only.
        <programlisting>
BEGIN

DELETE FROM budget_line
 WHERE budget_id IN (SELECT id from budget_info
                      WHERE id = in_id AND approved_by IS NULL);

DELETE FROM budget_to_project
 WHERE budget_id IN (SELECT id from budget_info
                      WHERE id = in_id AND approved_by IS NULL);

DELETE FROM budget_to_department
 WHERE budget_id IN (SELECT id from budget_info
                      WHERE id = in_id AND approved_by IS NULL);

DELETE FROM budget_info WHERE id = in_id AND approved_by IS NULL;

RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function budget__save_details(in_id integer, in_details text[]) -->
    <section id="public.function.budget-save-details-in-id-integer-in-details-textARRAY"
             xreflabel="()">
      <title id="public.function.budget-save-details-in-id-integer-in-details-textARRAY-title">
       budget__save_details(in_id integer, in_details text[])
      </title>
      <titleabbrev id="public.function.budget-save-details-in-id-integer-in-details-textARRAY-titleabbrev">
       budget__save_details(in_id integer, in_details text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
        This saves the line items for the budget.  in_details is an array n long
where each entry is {int account_id, text description, numeric amount}.  The
in_id parameter is the budget_id.
        <programlisting>
DECLARE
   loop_count int;
   retval budget_info_ext;
BEGIN
    FOR loop_count in
        array_lower(in_details, 1) ..
        array_upper(in_details, 1)
    LOOP
        INSERT INTO budget_line
                    (budget_id,
                     account_id,
                     description,
                     amount)
             VALUES (in_id,
                     in_details[loop_count][1]::int,
                     in_details[loop_count][2],
                     in_details[loop_count][3]::numeric);
    END LOOP;
    retval := budget__get_info(in_id);
    return retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function budget__save_info(in_id integer, in_start_date date, in_end_date date, in_reference text, in_description text, in_business_units integer[]) -->
    <section id="public.function.budget-save-info-in-id-integer-in-start-date-date-in-end-date-date-in-reference-text-in-description-text-in-business-units-integerARRAY"
             xreflabel="()">
      <title id="public.function.budget-save-info-in-id-integer-in-start-date-date-in-end-date-date-in-reference-text-in-description-text-in-business-units-integerARRAY-title">
       budget__save_info(in_id integer, in_start_date date, in_end_date date, in_reference text, in_description text, in_business_units integer[])
      </title>
      <titleabbrev id="public.function.budget-save-info-in-id-integer-in-start-date-date-in-end-date-date-in-reference-text-in-description-text-in-business-units-integerARRAY-titleabbrev">
       budget__save_info(in_id integer, in_start_date date, in_end_date date, in_reference text, in_description text, in_business_units integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
       Saves the extended budget info passed through to the function.  See the
comment on type budget_info_ext for more information.
        <programlisting>
DECLARE
   retval budget_info_ext;
   t_id int;
BEGIN

   PERFORM * FROM budget_info WHERE id = in_id and approved_by is not null;
   IF FOUND THEN
       RAISE EXCEPTION &#39;report approved&#39;;
   END IF;

  UPDATE budget_info
     SET start_date = in_start_date,
         end_date = in_end_date,
         reference = in_reference,
         description = in_description
   WHERE id = in_id and approved_by is null;
  IF FOUND THEN
      t_id := in_id;
  ELSE
       INSERT INTO budget_info (start_date, end_date, reference, description)
            VALUES (in_start_date, in_end_date, in_reference, in_description);
       t_id = currval(&#39;budget_info_id_seq&#39;);

       INSERT INTO budget_to_business_unit(budget_id, bu_id, bu_class)
       SELECT t_id, id, class_id
         FROM business_unit
        WHERE id = ANY(in_business_units);
  END IF;
  retval := budget__get_info(t_id);
  return retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function budget__save_note(in_id integer, in_subject text, in_note text) -->
    <section id="public.function.budget-save-note-in-id-integer-in-subject-text-in-note-text"
             xreflabel="()">
      <title id="public.function.budget-save-note-in-id-integer-in-subject-text-in-note-text-title">
       budget__save_note(in_id integer, in_subject text, in_note text)
      </title>
      <titleabbrev id="public.function.budget-save-note-in-id-integer-in-subject-text-in-note-text-titleabbrev">
       budget__save_note(in_id integer, in_subject text, in_note text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>budget_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves a note attached to a budget.
        <programlisting>
INSERT INTO budget_note (subject, note, ref_key)
     values ($2, $3, $1);

SELECT * FROM budget_note WHERE id = currval(&#39;note_id_seq&#39;::regclass);
</programlisting>
      </para>
    </section>

<!-- Function budget__search(in_start_date date, in_end_date date, in_includes_date date, in_reference text, in_description text, in_entered_by integer, in_approved_by integer, in_obsolete_by integer, in_business_units integer[], in_is_approved boolean, in_is_obsolete boolean) -->
    <section id="public.function.budget-search-in-start-date-date-in-end-date-date-in-includes-date-date-in-reference-text-in-description-text-in-entered-by-integer-in-approved-by-integer-in-obsolete-by-integer-in-business-units-integerARRAY-in-is-approved-boolean-in-is-obsolete-boolean"
             xreflabel="()">
      <title id="public.function.budget-search-in-start-date-date-in-end-date-date-in-includes-date-date-in-reference-text-in-description-text-in-entered-by-integer-in-approved-by-integer-in-obsolete-by-integer-in-business-units-integerARRAY-in-is-approved-boolean-in-is-obsolete-boolean-title">
       budget__search(in_start_date date, in_end_date date, in_includes_date date, in_reference text, in_description text, in_entered_by integer, in_approved_by integer, in_obsolete_by integer, in_business_units integer[], in_is_approved boolean, in_is_obsolete boolean)
      </title>
      <titleabbrev id="public.function.budget-search-in-start-date-date-in-end-date-date-in-includes-date-date-in-reference-text-in-description-text-in-entered-by-integer-in-approved-by-integer-in-obsolete-by-integer-in-business-units-integerARRAY-in-is-approved-boolean-in-is-obsolete-boolean-titleabbrev">
       budget__search(in_start_date date, in_end_date date, in_includes_date date, in_reference text, in_description text, in_entered_by integer, in_approved_by integer, in_obsolete_by integer, in_business_units integer[], in_is_approved boolean, in_is_obsolete boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF budget_info_ext</seg>
        </seglistitem>
       </segmentedlist>
 
        This is a general search for budgets
        <programlisting>
select bi.id, bi.start_date, bi.end_date, bi.reference, bi.description,
       bi.entered_by, bi.approved_by, bi.obsolete_by, bi.entered_at,
       bi.approved_at, bi.obsolete_at,
       ee.name, ae.name, oe.name
  from budget_info bi
  JOIN entity ee ON bi.entered_by = ee.id
  LEFT JOIN entity ae ON bi.approved_by = ae.id
  LEFT JOIN entity oe ON bi.obsolete_by = oe.id
 WHERE (start_date = $1 or $1 is null) AND ($2 = end_date or $2 is null)
       AND ($3 BETWEEN start_date AND end_date or $2 is null)
       AND ($4 ilike reference || &#39;%&#39; or $4 is null)
       AND (bi.description @@ plainto_tsquery($5) or $5 is null)
       AND ($6 = entered_by or $6 is null)
       AND ($7 = approved_by or $7 is null)
       AND ($8 = obsolete_by or $8 is null)
       AND ($10 IS NULL OR ($10 = (approved_by IS NOT NULL)))
       AND ($11 IS NULL OR ($11 = (obsolete_by IS NOT NULL)))
 ORDER BY reference;
</programlisting>
      </para>
    </section>

<!-- Function budget__variance_report(in_id integer) -->
    <section id="public.function.budget-variance-report-in-id-integer"
             xreflabel="()">
      <title id="public.function.budget-variance-report-in-id-integer-title">
       budget__variance_report(in_id integer)
      </title>
      <titleabbrev id="public.function.budget-variance-report-in-id-integer-titleabbrev">
       budget__variance_report(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF budget_variance_report</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves a variance report for budget with an id of in_id.
        <programlisting>
   WITH agg_account (amount, id, transdate)
        AS ( SELECT ac.amount *
                    CASE WHEN a.contra THEN -1 ELSE 1 END *
                    CASE WHEN a.category IN (&#39;A&#39;, &#39;E&#39;) THEN -1 ELSE 1 END
                    AS amount,
                    ac.chart_id, ac.transdate
               FROM acc_trans ac
               JOIN account a ON ac.chart_id = a.id
           )
   SELECT act.accno, act.description, act.id, b.description, b.amount,
          coalesce(sum(a.amount), 0),
          b.amount - coalesce(sum(a.amount), 0) AS variance
     FROM budget_info bi
     JOIN budget_line b ON bi.id = b.budget_id
     JOIN account act ON act.id = b.account_id
LEFT JOIN agg_account a ON a.transdate BETWEEN bi.start_date and bi.end_date
                           AND a.id = b.account_id
    WHERE bi.id = $1
 GROUP BY act.accno, act.description, act.id, b.description, b.amount
 ORDER BY act.accno;
</programlisting>
      </para>
    </section>

<!-- Function business_type__list() -->
    <section id="public.function.business-type-list"
             xreflabel="()">
      <title id="public.function.business-type-list-title">
       business_type__list()
      </title>
      <titleabbrev id="public.function.business-type-list-titleabbrev">
       business_type__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF business</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a list of all business types. Ordered by description by default.
        <programlisting>
        SELECT * FROM business ORDER BY description;
</programlisting>
      </para>
    </section>

<!-- Function business_unit__get(in_id integer) -->
    <section id="public.function.business-unit-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.business-unit-get-in-id-integer-title">
       business_unit__get(in_id integer)
      </title>
      <titleabbrev id="public.function.business-unit-get-in-id-integer-titleabbrev">
       business_unit__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>business_unit</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT * FROM business_unit where id = $1; </programlisting>
      </para>
    </section>

<!-- Function business_unit__get_tree_for(in_id integer) -->
    <section id="public.function.business-unit-get-tree-for-in-id-integer"
             xreflabel="()">
      <title id="public.function.business-unit-get-tree-for-in-id-integer-title">
       business_unit__get_tree_for(in_id integer)
      </title>
      <titleabbrev id="public.function.business-unit-get-tree-for-in-id-integer-titleabbrev">
       business_unit__get_tree_for(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF business_unit_short</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns tree-related records with the root of the tree being
the business unit of in_id.  
        <programlisting>
WITH RECURSIVE tree  (id, control_code, description,  start_date, end_date,
                      parent_id, path, level)
AS (
   SELECT id, control_code, description, start_date, end_date, parent_id,
          ARRAY[parent_id] AS path, 1 as level
     FROM business_unit WHERE $1 = id
    UNION
   SELECT t.id, t.control_code, t.description, t.start_date, t.end_date,
          t.parent_id,
          t.path || bu.id AS path, t.level + 1 as level
     FROM business_unit bu JOIN tree t ON t.parent_id = bu.id
)
SELECT * FROM tree ORDER BY path;
</programlisting>
      </para>
    </section>

<!-- Function business_unit__list_by_class(in_business_unit_class_id integer, in_active_on date, in_credit_id integer, in_strict_credit boolean) -->
    <section id="public.function.business-unit-list-by-class-in-business-unit-class-id-integer-in-active-on-date-in-credit-id-integer-in-strict-credit-boolean"
             xreflabel="()">
      <title id="public.function.business-unit-list-by-class-in-business-unit-class-id-integer-in-active-on-date-in-credit-id-integer-in-strict-credit-boolean-title">
       business_unit__list_by_class(in_business_unit_class_id integer, in_active_on date, in_credit_id integer, in_strict_credit boolean)
      </title>
      <titleabbrev id="public.function.business-unit-list-by-class-in-business-unit-class-id-integer-in-active-on-date-in-credit-id-integer-in-strict-credit-boolean-titleabbrev">
       business_unit__list_by_class(in_business_unit_class_id integer, in_active_on date, in_credit_id integer, in_strict_credit boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF business_unit</seg>
        </seglistitem>
       </segmentedlist>
 
        This function retUrns a list of all units (projects, departments, funds, etc)
active on the in_active_on date, where in_credit_id matches the credit id of the
customer or vendor requested, and where in_business_uni_class_id is the class id
of the class of business units (1 for department, 2 for project, etc).

With the exception of in_business_unit_class_id, the null matches all records.

        <programlisting>
SELECT * FROM business_unit
              WHERE (in_active_on BETWEEN coalesce(start_date, in_active_on)
                                      AND coalesce(end_date, in_active_on)
                      OR in_active_on IS NULL)
                    AND (in_credit_id = credit_id
                        OR (credit_id IS NULL and in_strict_credit IS NOT TRUE)
                        OR (in_credit_id IS NULL))
                    AND class_id = in_business_unit_class_id
           ORDER BY control_code;
</programlisting>
      </para>
    </section>

<!-- Function business_unit__list_classes(in_active boolean, in_module text) -->
    <section id="public.function.business-unit-list-classes-in-active-boolean-in-module-text"
             xreflabel="()">
      <title id="public.function.business-unit-list-classes-in-active-boolean-in-module-text-title">
       business_unit__list_classes(in_active boolean, in_module text)
      </title>
      <titleabbrev id="public.function.business-unit-list-classes-in-active-boolean-in-module-text-titleabbrev">
       business_unit__list_classes(in_active boolean, in_module text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF business_unit_class</seg>
        </seglistitem>
       </segmentedlist>
 
        This function lists all business unit clases.  If in_active is true, then
only active classes are listed.  If it is false then only inactive classes are
listed.  If it is null, then all classes are listed.
        <programlisting>

SELECT bc.*
  FROM business_unit_class bc
 WHERE     (active = $1 OR $1 IS NULL)
       AND (id IN (select bu_class_id
                     FROM bu_class_to_module bcm
                     JOIN lsmb_module mod ON mod.id = bcm.module_id
                    WHERE lower(label) = lower($2))
            OR $2 is null)
ORDER BY ordering;

</programlisting>
      </para>
    </section>

<!-- Function business_unit__save(in_id integer, in_class_id integer, in_control_code text, in_description text, in_start_date date, in_end_date date, in_parent_id integer, in_credit_id integer) -->
    <section id="public.function.business-unit-save-in-id-integer-in-class-id-integer-in-control-code-text-in-description-text-in-start-date-date-in-end-date-date-in-parent-id-integer-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.business-unit-save-in-id-integer-in-class-id-integer-in-control-code-text-in-description-text-in-start-date-date-in-end-date-date-in-parent-id-integer-in-credit-id-integer-title">
       business_unit__save(in_id integer, in_class_id integer, in_control_code text, in_description text, in_start_date date, in_end_date date, in_parent_id integer, in_credit_id integer)
      </title>
      <titleabbrev id="public.function.business-unit-save-in-id-integer-in-class-id-integer-in-control-code-text-in-description-text-in-start-date-date-in-end-date-date-in-parent-id-integer-in-credit-id-integer-titleabbrev">
       business_unit__save(in_id integer, in_class_id integer, in_control_code text, in_description text, in_start_date date, in_end_date date, in_parent_id integer, in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>business_unit</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval business_unit;
        t_id int;

BEGIN

UPDATE business_unit
   SET class_id = in_class_id,
       control_code = in_control_code,
       description = in_description,
       start_date = in_start_date,
       end_date = in_end_date,
       credit_id = in_credit_id
 WHERE id = in_id;


IF FOUND THEN
   t_id := in_id;
ELSE
   INSERT INTO business_unit
          (class_id, control_code, description, start_date, end_date, parent_id,
           credit_id)
   VALUES (in_class_id, in_control_code, in_description, in_start_date,
           in_end_date, in_parent_id, in_credit_id);
    t_id := currval(&#39;business_unit_id_seq&#39;);
END IF;

SELECT * INTO retval FROM business_unit WHERE id = t_id;

RETURN retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function business_unit_class__get_modules(in_id integer) -->
    <section id="public.function.business-unit-class-get-modules-in-id-integer"
             xreflabel="()">
      <title id="public.function.business-unit-class-get-modules-in-id-integer-title">
       business_unit_class__get_modules(in_id integer)
      </title>
      <titleabbrev id="public.function.business-unit-class-get-modules-in-id-integer-titleabbrev">
       business_unit_class__get_modules(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF lsmb_module</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT * FROM lsmb_module
    WHERE id IN (select module_id from bu_class_to_module where bu_class_id = $1)
 ORDER BY id;
</programlisting>
      </para>
    </section>

<!-- Function business_unit_class__save(in_id integer, in_label text, in_active boolean, in_ordering integer) -->
    <section id="public.function.business-unit-class-save-in-id-integer-in-label-text-in-active-boolean-in-ordering-integer"
             xreflabel="()">
      <title id="public.function.business-unit-class-save-in-id-integer-in-label-text-in-active-boolean-in-ordering-integer-title">
       business_unit_class__save(in_id integer, in_label text, in_active boolean, in_ordering integer)
      </title>
      <titleabbrev id="public.function.business-unit-class-save-in-id-integer-in-label-text-in-active-boolean-in-ordering-integer-titleabbrev">
       business_unit_class__save(in_id integer, in_label text, in_active boolean, in_ordering integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>business_unit_class</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval business_unit_class;
        t_id int;
BEGIN

t_id := in_id;
UPDATE business_unit_class
   SET label = in_label,
       active = in_active,
       ordering = in_ordering
 WHERE id = in_id;

IF NOT FOUND THEN

   INSERT INTO business_unit_class (label, active, ordering)
   VALUES (in_label, in_active, in_ordering);

   t_id := currval(&#39;business_unit_class_id_seq&#39;);

END IF;

SELECT * INTO retval FROM business_unit_class WHERE id = t_id;

RETURN retval;

END;

</programlisting>
      </para>
    </section>

<!-- Function business_unit_class__save_modules(in_id integer, in_mod_ids integer[]) -->
    <section id="public.function.business-unit-class-save-modules-in-id-integer-in-mod-ids-integerARRAY"
             xreflabel="()">
      <title id="public.function.business-unit-class-save-modules-in-id-integer-in-mod-ids-integerARRAY-title">
       business_unit_class__save_modules(in_id integer, in_mod_ids integer[])
      </title>
      <titleabbrev id="public.function.business-unit-class-save-modules-in-id-integer-in-mod-ids-integerARRAY-titleabbrev">
       business_unit_class__save_modules(in_id integer, in_mod_ids integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DELETE FROM bu_class_to_module WHERE bu_class_id = $1;

INSERT INTO bu_class_to_module (bu_class_id, module_id)
SELECT $1, unnest
  FROM unnest($2);

SELECT true;
</programlisting>
      </para>
    </section>

<!-- Function business_unit_get(in_id integer) -->
    <section id="public.function.business-unit-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.business-unit-get-in-id-integer-title">
       business_unit_get(in_id integer)
      </title>
      <titleabbrev id="public.function.business-unit-get-in-id-integer-titleabbrev">
       business_unit_get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>business_unit</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT * FROM business_unit WHERE id = $1; </programlisting>
      </para>
    </section>

<!-- Function chart_get_ar_ap(in_account_class integer) -->
    <section id="public.function.chart-get-ar-ap-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.chart-get-ar-ap-in-account-class-integer-title">
       chart_get_ar_ap(in_account_class integer)
      </title>
      <titleabbrev id="public.function.chart-get-ar-ap-in-account-class-integer-titleabbrev">
       chart_get_ar_ap(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF chart</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns the cash account according with in_account_class which
must be 1 or 2.

If in_account_class is 1 then it returns a list of AP accounts, and if
in_account_class is 2, then a list of AR accounts.
        <programlisting>
DECLARE out_row chart%ROWTYPE;
BEGIN
        IF in_account_class NOT IN (1, 2) THEN
                RAISE EXCEPTION &#39;Bad Account Type&#39;;
        END IF;
       FOR out_row IN
               SELECT * FROM chart
               WHERE link = CASE WHEN in_account_class = 1 THEN &#39;AP&#39;
                               WHEN in_account_class = 2 THEN &#39;AR&#39;
                               END
               ORDER BY accno
       LOOP
               RETURN NEXT out_row;
       END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function chart_list_all() -->
    <section id="public.function.chart-list-all"
             xreflabel="()">
      <title id="public.function.chart-list-all-title">
       chart_list_all()
      </title>
      <titleabbrev id="public.function.chart-list-all-titleabbrev">
       chart_list_all()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF chart</seg>
        </seglistitem>
       </segmentedlist>
 
        Generates a list of chart view entries.
        <programlisting>
SELECT * FROM chart ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function chart_list_cash(in_account_class integer) -->
    <section id="public.function.chart-list-cash-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.chart-list-cash-in-account-class-integer-title">
       chart_list_cash(in_account_class integer)
      </title>
      <titleabbrev id="public.function.chart-list-cash-in-account-class-integer-titleabbrev">
       chart_list_cash(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF chart</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns the overpayment accounts acording with
in_account_class which must be 1 or 2.

If in_account_class is 1 it returns a list of AP cash accounts and
if 2, AR cash accounts.
        <programlisting>
 DECLARE resultrow record;
         link_string text;
 BEGIN
         IF in_account_class = 1 THEN
            link_string := &#39;%AP_paid%&#39;;
         ELSE
            link_string := &#39;%AR_paid%&#39;;
         END IF;

         FOR resultrow IN
           SELECT *  FROM chart
           WHERE link LIKE link_string
           ORDER BY accno
           LOOP
           return next resultrow;
         END LOOP;
 END;
</programlisting>
      </para>
    </section>

<!-- Function chart_list_discount(in_account_class integer) -->
    <section id="public.function.chart-list-discount-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.chart-list-discount-in-account-class-integer-title">
       chart_list_discount(in_account_class integer)
      </title>
      <titleabbrev id="public.function.chart-list-discount-in-account-class-integer-titleabbrev">
       chart_list_discount(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF chart</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns the discount accounts acording with in_account_class
which must be 1 or 2.

If in_account_class is 1, returns AP discount accounts, if 2, AR discount
accounts.
        <programlisting>
DECLARE resultrow record;
        link_string text;
BEGIN
        IF in_account_class = 1 THEN
           link_string := &#39;%AP_discount%&#39;;
        ELSE
           link_string := &#39;%AR_discount%&#39;;
        END IF;

        FOR resultrow IN
          SELECT *  FROM chart
          WHERE link LIKE link_string
          ORDER BY accno
          LOOP
          return next resultrow;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function chart_list_overpayment(in_account_class integer) -->
    <section id="public.function.chart-list-overpayment-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.chart-list-overpayment-in-account-class-integer-title">
       chart_list_overpayment(in_account_class integer)
      </title>
      <titleabbrev id="public.function.chart-list-overpayment-in-account-class-integer-titleabbrev">
       chart_list_overpayment(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF chart</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of AP_overpayment accounts if in_account_class is 1
Otherwise it returns a list of AR_overpayment accounts.
        <programlisting>
DECLARE resultrow record;
        link_string text;
BEGIN
        IF in_account_class = 1 THEN
           link_string := &#39;%AP_overpayment%&#39;;
        ELSE
           link_string := &#39;%AR_overpayment%&#39;;
        END IF;

        FOR resultrow IN
          SELECT *  FROM chart
          WHERE link LIKE link_string
          ORDER BY accno
          LOOP
          return next resultrow;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function chart_list_search(in_search text, in_link_desc text) -->
    <section id="public.function.chart-list-search-in-search-text-in-link-desc-text"
             xreflabel="()">
      <title id="public.function.chart-list-search-in-search-text-in-link-desc-text-title">
       chart_list_search(in_search text, in_link_desc text)
      </title>
      <titleabbrev id="public.function.chart-list-search-in-search-text-in-link-desc-text-titleabbrev">
       chart_list_search(in_search text, in_link_desc text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        This returns a list of account entries where the description or account
number begins with in_search.

If in_link_desc is provided, the list is further filtered by which accounts are
set to an account_link.description equal to that provided.
        <programlisting>
                SELECT * FROM account
                 WHERE (accno ~* (&#39;^&#39;||in_search)
                       OR description ~* (&#39;^&#39;||in_search))
                       AND (in_link_desc IS NULL
                           or id in
                          (select account_id from account_link
                            where description = in_link_desc))
                       AND not obsolete
              ORDER BY accno
</programlisting>
      </para>
    </section>

<!-- Function check_expiration() -->
    <section id="public.function.check-expiration"
             xreflabel="()">
      <title id="public.function.check-expiration-title">
       check_expiration()
      </title>
      <titleabbrev id="public.function.check-expiration-titleabbrev">
       check_expiration()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This checks whether the user needs to be notified of a pending expiration of
his/her password.  Returns true if needed, false if not.

The function also records the next time when the notification will again need to
be displayed. 
        <programlisting>
DECLARE test_result BOOL;
        expires_in interval;
        notify_again interval;
BEGIN
        expires_in := user__check_my_expiration();

        SELECT expires_in &lt; notify_password INTO test_result
        FROM users WHERE username = SESSION_USER;

        IF test_result THEN
                IF expires_in &lt; &#39;1 week&#39; THEN
                        notify_again := &#39;1 hour&#39;;
                ELSE
                        notify_again := &#39;1 day&#39;;
                END IF;

                UPDATE users
                SET notify_password = expires_in - notify_again
                WHERE username = SESSION_USER;
        END IF;
        RETURN test_result;
END;
</programlisting>
      </para>
    </section>

<!-- Function cogs__add_for_ap(in_parts_id integer, in_qty numeric, in_lastcost numeric) -->
    <section id="public.function.cogs-add-for-ap-in-parts-id-integer-in-qty-numeric-in-lastcost-numeric"
             xreflabel="()">
      <title id="public.function.cogs-add-for-ap-in-parts-id-integer-in-qty-numeric-in-lastcost-numeric-title">
       cogs__add_for_ap(in_parts_id integer, in_qty numeric, in_lastcost numeric)
      </title>
      <titleabbrev id="public.function.cogs-add-for-ap-in-parts-id-integer-in-qty-numeric-in-lastcost-numeric-titleabbrev">
       cogs__add_for_ap(in_parts_id integer, in_qty numeric, in_lastcost numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE t_alloc numeric := 0;
        t_cogs numeric := 0;
        t_inv invoice;
        t_cp account_checkpoint;
        t_ar ar;
        t_avail numeric;
BEGIN


IF in_qty &gt; 0 THEN
   return (cogs__reverse_ap(in_parts_id, in_qty * -1))[1] * in_lastcost;
END IF;

SELECT * INTO t_cp FROM account_checkpoint ORDER BY end_date DESC LIMIT 1;

FOR t_inv IN
    SELECT i.*
      FROM invoice i
      JOIN (select id, approved, transdate from ar
             union
            select id, approved, transdate from gl) a
           ON a.id = i.trans_id AND a.approved
     WHERE qty + allocated &gt; 0 and parts_id  = in_parts_id
  ORDER BY a.transdate, a.id, i.id
LOOP
   t_avail := t_inv.qty + t_inv.allocated;
   SELECT * INTO t_ar FROM ar WHERE id = t_inv.trans_id;
   IF t_alloc &lt; in_qty THEN
       RAISE EXCEPTION &#39;TOO MANY ALLOCATED&#39;;
   ELSIF t_alloc = in_qty THEN
       return t_alloc;
   ELSIF (in_qty + t_alloc) * -1 &lt;=  t_avail  THEN
       UPDATE invoice SET allocated = allocated + (in_qty + t_alloc)
        WHERE id = t_inv.id;

       INSERT INTO acc_trans
              (chart_id, transdate, amount, invoice_id, approved, trans_id)
       SELECT expense_accno_id,
              CASE WHEN t_ar.transdate &gt; coalesce(t_cp.end_date, t_ar.transdate - 1) THEN t_ar.transdate
                   ELSE t_cp.end_date + &#39;1 day&#39;::interval
               END, (in_qty + t_alloc) * in_lastcost, t_inv.id, true,
              t_inv.trans_id
         FROM parts
       WHERE  id = t_inv.parts_id AND inventory_accno_id IS NOT NULL
              AND expense_accno_id IS NOT NULL
       UNION
       SELECT income_accno_id,
              CASE WHEN t_ar.transdate &gt; coalesce(t_cp.end_date, t_ar.transdate - 1) THEN t_ar.transdate
                   ELSE t_cp.end_date + &#39;1 day&#39;::interval
               END, -1 * (in_qty + t_alloc) * in_lastcost, t_inv.id, true,
              t_inv.trans_id
         FROM parts
       WHERE  id = t_inv.parts_id AND inventory_accno_id IS NOT NULL
              AND expense_accno_id IS NOT NULL;

       t_cogs := t_cogs + (in_qty + t_alloc) * in_lastcost;
       return in_qty * -1;
   ELSE
       UPDATE invoice SET allocated = qty * -1
        WHERE id = t_inv.id;
       t_cogs := t_cogs + t_avail * in_lastcost;

       INSERT INTO acc_trans
              (chart_id, transdate, amount, invoice_id, approved, trans_id)
       SELECT expense_accno_id,
              CASE WHEN t_ar.transdate &gt; coalesce(t_cp.end_date, t_ar.transdate - 1) THEN t_ar.transdate
                   ELSE t_cp.end_date + &#39;1 day&#39;::interval
               END,  -1 * t_avail * in_lastcost,
              t_inv.id, true, t_inv.trans_id
         FROM parts
       WHERE  id = t_inv.parts_id AND inventory_accno_id IS NOT NULL
              AND expense_accno_id IS NOT NULL
       UNION
       SELECT income_accno_id,
              CASE WHEN t_ar.transdate &gt; coalesce(t_cp.end_date, t_ar.transdate - 1) THEN t_ar.transdate
                   ELSE t_cp.end_date + &#39;1 day&#39;::interval
               END, -t_avail * in_lastcost, t_inv.id, true, t_inv.trans_id
         FROM parts
       WHERE  id = t_inv.parts_id AND inventory_accno_id IS NOT NULL
              AND expense_accno_id IS NOT NULL;
       t_alloc := t_alloc + t_avail;
       t_cogs := t_cogs + t_avail * in_lastcost;
   END IF;


END LOOP;

RETURN t_alloc;
END;
</programlisting>
      </para>
    </section>

<!-- Function cogs__add_for_ap_line(in_invoice_id integer) -->
    <section id="public.function.cogs-add-for-ap-line-in-invoice-id-integer"
             xreflabel="()">
      <title id="public.function.cogs-add-for-ap-line-in-invoice-id-integer-title">
       cogs__add_for_ap_line(in_invoice_id integer)
      </title>
      <titleabbrev id="public.function.cogs-add-for-ap-line-in-invoice-id-integer-titleabbrev">
       cogs__add_for_ap_line(in_invoice_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval numeric;
        r_cogs numeric[];
        t_inv invoice;
        t_adj numeric;
        t_ap  ap;
BEGIN

SELECT * INTO t_inv FROM invoice
 WHERE id = in_invoice_id;

IF t_inv.qty + t_inv.allocated = 0 THEN
   return 0;
END IF;

SELECT * INTO t_ap FROM ap WHERE id = t_inv.trans_id;

IF t_inv.qty &lt; 0 THEN -- normal COGS

    SELECT cogs__add_for_ap(i.parts_id, i.qty + i.allocated, i.sellprice)
      INTO retval
      FROM invoice i
      JOIN parts p ON p.id = i.parts_id
     WHERE i.id = $1;

    UPDATE invoice
       SET allocated = allocated + retval
     WHERE id = $1;
ELSE -- reversal

   r_cogs := cogs__reverse_ap(t_inv.parts_id, t_inv.qty + t_inv.allocated);

   UPDATE invoice
      SET allocated = allocated + r_cogs[1]
    WHERE id = in_invoice_id;

   t_adj := t_inv.sellprice * r_cogs[1] + r_cogs[2];

   INSERT INTO acc_trans
          (chart_id, trans_id, approved,  amount, transdate, invoice_id)
   SELECT p.inventory_accno_id, t_inv.trans_id, true, t_adj, t_ap.transdate,
          in_invoice_id
     FROM parts p
    WHERE id = t_inv.parts_id
    UNION
   SELECT p.expense_accno_id, t_inv.trans_id, true, t_adj * -1, t_ap.transdate,
          in_invoice_id
     FROM parts p
    WHERE id = t_inv.parts_id;
   retval := r_cogs[1];
   raise notice &#39;cogs reversal returned %&#39;, r_cogs;

END IF;

RETURN retval;

END;

</programlisting>
      </para>
    </section>

<!-- Function cogs__add_for_ar(in_parts_id integer, in_qty numeric) -->
    <section id="public.function.cogs-add-for-ar-in-parts-id-integer-in-qty-numeric"
             xreflabel="()">
      <title id="public.function.cogs-add-for-ar-in-parts-id-integer-in-qty-numeric-title">
       cogs__add_for_ar(in_parts_id integer, in_qty numeric)
      </title>
      <titleabbrev id="public.function.cogs-add-for-ar-in-parts-id-integer-in-qty-numeric-titleabbrev">
       cogs__add_for_ar(in_parts_id integer, in_qty numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric[]</seg>
        </seglistitem>
       </segmentedlist>
 
        This function accepts a parts_id and a quantity, and iterates through AP
records in order, calculating COGS on a FIFO basis and returning it to the
application to attach to the current transaction.

Return values are an array of {allocated, cogs}.

        <programlisting>
DECLARE t_alloc numeric := 0;
        t_cogs numeric := 0;
        t_inv invoice;
        t_avail numeric;
BEGIN


FOR t_inv IN
    SELECT i.*
      FROM invoice i
      JOIN (select id, approved, transdate from ap
             union
            select id, approved, transdate from gl) a ON a.id = i.trans_id
     WHERE qty + allocated &lt; 0 AND i.parts_id = in_parts_id AND a.approved
  ORDER BY a.transdate asc, a.id asc, i.id asc
LOOP
   t_avail := (t_inv.qty + t_inv.allocated) * -1;
   IF t_alloc &gt; in_qty THEN
       RAISE EXCEPTION &#39;TOO MANY ALLOCATED&#39;;
   ELSIF t_alloc = in_qty THEN
       return ARRAY[t_alloc, t_cogs];
   ELSIF (in_qty + t_alloc) &lt;= t_avail THEN
       UPDATE invoice SET allocated = allocated + (in_qty - t_alloc)
        WHERE id = t_inv.id;
       t_cogs := t_cogs + (in_qty - t_alloc) * t_inv.sellprice;
       t_alloc := in_qty;
       return ARRAY[t_alloc, t_cogs];
   ELSE
       UPDATE invoice SET allocated = qty * -1
        WHERE id = t_inv.id;
       t_cogs := t_cogs + (t_avail * t_inv.sellprice);
       t_alloc := t_alloc + t_avail;
   END IF;
END LOOP;

RETURN ARRAY[t_alloc, t_cogs];

END;
</programlisting>
      </para>
    </section>

<!-- Function cogs__add_for_ar_line(in_invoice_id integer) -->
    <section id="public.function.cogs-add-for-ar-line-in-invoice-id-integer"
             xreflabel="()">
      <title id="public.function.cogs-add-for-ar-line-in-invoice-id-integer-title">
       cogs__add_for_ar_line(in_invoice_id integer)
      </title>
      <titleabbrev id="public.function.cogs-add-for-ar-line-in-invoice-id-integer-titleabbrev">
       cogs__add_for_ar_line(in_invoice_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
   t_cogs numeric[];
   t_inv invoice;
   t_part parts;
   t_ar ar;
   t_transdate date;
   t_override_cogs int;
BEGIN

SELECT * INTO t_inv FROM invoice WHERE id = in_invoice_id;
SELECT * INTO t_part FROM parts WHERE id = t_inv.parts_id;
SELECT * INTO t_ar FROM ar WHERE id = t_inv.trans_id;

IF t_ar.is_return THEN
   t_override_cogs = (setting_get(&#39;ar_return_account_id&#39;)).value::int;
END IF;

IF t_part.inventory_accno_id IS NULL THEN
   RETURN 0;
END IF;

IF t_inv.qty + t_inv.allocated = 0 THEN
   return 0;
END IF;

IF t_inv.qty &gt; 0 THEN
   t_cogs := cogs__add_for_ar(t_inv.parts_id, t_inv.qty + t_inv.allocated);
ELSE
   t_cogs := cogs__reverse_ar(t_inv.parts_id, t_inv.qty + t_inv.allocated);
END IF;


UPDATE invoice set allocated = allocated - t_cogs[1]
 WHERE id = in_invoice_id;

SELECT CASE WHEN t_ar.transdate &gt; coalesce(max(end_date), t_ar.transdate - 1) THEN t_ar.transdate
            ELSE max(end_date) + &#39;1 day&#39;::interval
        END INTO t_transdate
  from account_checkpoint td;
INSERT INTO acc_trans
       (trans_id, chart_id, approved, amount, transdate,  invoice_id)
VALUES (t_inv.trans_id, COALESCE(t_override_cogs,
                      CASE WHEN t_inv.qty &lt; 0 AND t_ar.is_return
                           THEN t_part.returns_accno_id
                           ELSE t_part.expense_accno_id
                      END), TRUE, t_cogs[2] * -1,
       coalesce(t_transdate, t_ar.transdate), t_inv.id),
       (t_inv.trans_id, t_part.inventory_accno_id, TRUE, t_cogs[2],
       t_transdate, t_inv.id);

RETURN t_cogs[1];

END;

</programlisting>
      </para>
    </section>

<!-- Function cogs__reverse_ap(in_parts_id integer, in_qty numeric) -->
    <section id="public.function.cogs-reverse-ap-in-parts-id-integer-in-qty-numeric"
             xreflabel="()">
      <title id="public.function.cogs-reverse-ap-in-parts-id-integer-in-qty-numeric-title">
       cogs__reverse_ap(in_parts_id integer, in_qty numeric)
      </title>
      <titleabbrev id="public.function.cogs-reverse-ap-in-parts-id-integer-in-qty-numeric-titleabbrev">
       cogs__reverse_ap(in_parts_id integer, in_qty numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric[]</seg>
        </seglistitem>
       </segmentedlist>
 
        This function iterates through invoice rows attached to ap transactions and
allocates them on a first-in first-out basis.  The sort of pseudo-&quot;COGS&quot; value
is returned to the application for further handling.
        <programlisting>
DECLARE t_alloc numeric :=0;
        t_inv invoice;
        t_cogs numeric :=0;
        retval numeric[];
BEGIN

FOR t_inv IN
    SELECT i.*
      FROM invoice i
      JOIN (select id, approved, transdate from ap
             union
            select id, approved, transdate from gl) a
           ON a.id = i.trans_id AND a.approved
     WHERE qty + allocated &lt; 0 AND parts_id = in_parts_id
  ORDER BY a.transdate, a.id, i.id
LOOP
   IF t_alloc &gt; in_qty THEN
       RAISE EXCEPTION &#39;TOO MANY ALLOCATED&#39;;
   ELSIF t_alloc = in_qty THEN
       return ARRAY[t_alloc, t_cogs];
   ELSIF (in_qty - t_alloc) &lt;= -1 * (t_inv.qty + t_inv.allocated) THEN
       raise notice &#39;partial reversal&#39;;
       UPDATE invoice SET allocated = allocated + (in_qty - t_alloc)
        WHERE id = t_inv.id;
       return ARRAY[in_qty * -1, t_cogs + (in_qty - t_alloc) * t_inv.sellprice];
   ELSE
       raise notice &#39;total reversal&#39;;
       UPDATE invoice SET allocated = qty * -1
        WHERE id = t_inv.id;
       t_alloc := t_alloc - (t_inv.qty + t_inv.allocated);
       t_cogs := t_cogs - (t_inv.qty + t_inv.allocated) * t_inv.sellprice;
   END IF;
END LOOP;

RETURN ARRAY[t_alloc, t_cogs];

RAISE EXCEPTION &#39;TOO FEW TO ALLOCATE&#39;;
END;
</programlisting>
      </para>
    </section>

<!-- Function cogs__reverse_ar(in_parts_id integer, in_qty numeric) -->
    <section id="public.function.cogs-reverse-ar-in-parts-id-integer-in-qty-numeric"
             xreflabel="()">
      <title id="public.function.cogs-reverse-ar-in-parts-id-integer-in-qty-numeric-title">
       cogs__reverse_ar(in_parts_id integer, in_qty numeric)
      </title>
      <titleabbrev id="public.function.cogs-reverse-ar-in-parts-id-integer-in-qty-numeric-titleabbrev">
       cogs__reverse_ar(in_parts_id integer, in_qty numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric[]</seg>
        </seglistitem>
       </segmentedlist>
 
       This function accepts a part id and quantity to reverse.  It then iterates
backwards over AP related records, calculating COGS.  This does not save COGS
but rather returns it to the application to save.

Return values are an array of {allocated, cogs}.

        <programlisting>
DECLARE t_alloc numeric := 0; -- qty to reverse (negative)
        t_cogs numeric := 0;
        t_inv invoice;
        t_reversed numeric;
        t_reallocated numeric;
BEGIN

IF in_qty = 0 THEN
   RETURN ARRAY[0, 0];
END IF;

FOR t_inv IN
    SELECT i.*
      FROM invoice i
      JOIN (SELECT id, approved, transdate FROM ar
            UNION
            SELECT id, approved, transdate FROM gl) a ON a.id = i.trans_id
     WHERE allocated + qty &gt; 0 and a.approved and parts_id = in_parts_id
   ORDER BY a.transdate ASC, a.id ASC, i.id ASC
LOOP
   t_reallocated := greatest(in_qty - t_alloc, t_inv.qty + t_inv.allocated);
   UPDATE invoice
      SET allocated = allocated - t_reallocated
    WHERE id = t_inv.id;
   t_alloc := t_alloc - t_reallocated;

   IF t_alloc &lt; in_qty THEN
      RAISE EXCEPTION &#39;TOO MANY ALLOCATED (1)&#39;;
   ELSIF t_alloc = in_qty THEN
      RETURN ARRAY[t_alloc, 0];
   END IF;
END LOOP;

FOR t_inv IN
    SELECT i.*
      FROM invoice i
      JOIN (select id, approved, transdate from ap
            union
            select id, approved, transdate from gl) a ON a.id = i.trans_id
     WHERE allocated &gt; 0 and a.approved and parts_id = in_parts_id
  ORDER BY a.transdate DESC, a.id DESC, i.id DESC
LOOP
   t_reversed := least((in_qty - t_alloc) * -1, t_inv.allocated);
   UPDATE invoice SET allocated = allocated - t_reversed
    WHERE id = t_inv.id;
   t_cogs := t_cogs - t_reversed * t_inv.sellprice;
   t_alloc := t_alloc - t_reversed;

   IF t_alloc &lt; in_qty THEN
       RAISE EXCEPTION &#39;TOO MANY ALLOCATED&#39;;
   ELSIF t_alloc = in_qty THEN
       RETURN ARRAY[t_alloc, t_cogs];
   END IF;
END LOOP;

END;
</programlisting>
      </para>
    </section>

<!-- Function company__get(in_entity_id integer) -->
    <section id="public.function.company-get-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.company-get-in-entity-id-integer-title">
       company__get(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.company-get-in-entity-id-integer-titleabbrev">
       company__get(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>company_entity</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns all attributes for the company attached to the entity.
        <programlisting>
        SELECT c.entity_id, e.entity_class, c.legal_name, c.tax_id, c.sales_tax_id,
               c.license_number, c.sic_code, e.control_code, e.country_id
          FROM company c
          JOIN entity e ON e.id = c.entity_id
         WHERE entity_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function company__get_all_accounts(in_entity_id integer, in_entity_class integer) -->
    <section id="public.function.company-get-all-accounts-in-entity-id-integer-in-entity-class-integer"
             xreflabel="()">
      <title id="public.function.company-get-all-accounts-in-entity-id-integer-in-entity-class-integer-title">
       company__get_all_accounts(in_entity_id integer, in_entity_class integer)
      </title>
      <titleabbrev id="public.function.company-get-all-accounts-in-entity-id-integer-in-entity-class-integer-titleabbrev">
       company__get_all_accounts(in_entity_id integer, in_entity_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_credit_account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of all entity credit accounts attached to that entity.
        <programlisting>

    SELECT *
      FROM entity_credit_account
     WHERE entity_id = $1
       AND entity_class = $2;

</programlisting>
      </para>
    </section>

<!-- Function company__get_by_cc(in_control_code text) -->
    <section id="public.function.company-get-by-cc-in-control-code-text"
             xreflabel="()">
      <title id="public.function.company-get-by-cc-in-control-code-text-title">
       company__get_by_cc(in_control_code text)
      </title>
      <titleabbrev id="public.function.company-get-by-cc-in-control-code-text-titleabbrev">
       company__get_by_cc(in_control_code text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>company_entity</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the entity/company row attached to the control code. 
        <programlisting>
        SELECT c.entity_id, e.entity_class, c.legal_name, c.tax_id, c.sales_tax_id,
               c.license_number, c.sic_code, e.control_code, e.country_id
          FROM company c
          JOIN entity e ON e.id = c.entity_id
         WHERE e.control_code = $1;
</programlisting>
      </para>
    </section>

<!-- Function company__next_id() -->
    <section id="public.function.company-next-id"
             xreflabel="()">
      <title id="public.function.company-next-id-title">
       company__next_id()
      </title>
      <titleabbrev id="public.function.company-next-id-titleabbrev">
       company__next_id()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>bigint</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    select nextval(&#39;company_id_seq&#39;);

</programlisting>
      </para>
    </section>

<!-- Function company__save(in_control_code text, in_entity_class integer, in_legal_name text, in_tax_id text, in_entity_id integer, in_sic_code text, in_country_id integer, in_sales_tax_id text, in_license_number text) -->
    <section id="public.function.company-save-in-control-code-text-in-entity-class-integer-in-legal-name-text-in-tax-id-text-in-entity-id-integer-in-sic-code-text-in-country-id-integer-in-sales-tax-id-text-in-license-number-text"
             xreflabel="()">
      <title id="public.function.company-save-in-control-code-text-in-entity-class-integer-in-legal-name-text-in-tax-id-text-in-entity-id-integer-in-sic-code-text-in-country-id-integer-in-sales-tax-id-text-in-license-number-text-title">
       company__save(in_control_code text, in_entity_class integer, in_legal_name text, in_tax_id text, in_entity_id integer, in_sic_code text, in_country_id integer, in_sales_tax_id text, in_license_number text)
      </title>
      <titleabbrev id="public.function.company-save-in-control-code-text-in-entity-class-integer-in-legal-name-text-in-tax-id-text-in-entity-id-integer-in-sic-code-text-in-country-id-integer-in-sales-tax-id-text-in-license-number-text-titleabbrev">
       company__save(in_control_code text, in_entity_class integer, in_legal_name text, in_tax_id text, in_entity_id integer, in_sic_code text, in_country_id integer, in_sales_tax_id text, in_license_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>company</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves a company.  Returns the id number of the record stored.
        <programlisting>
DECLARE t_entity_id INT;
        t_control_code TEXT;
        t_retval COMPANY;
BEGIN

        IF in_control_code IS NULL THEN
                t_control_code := setting_increment(&#39;entity_control&#39;);
        ELSE
                t_control_code := in_control_code;
        END IF;

        UPDATE entity
        SET name = in_legal_name,
                entity_class = in_entity_class,
                control_code = t_control_code,
                country_id   = in_country_id
        WHERE id = in_entity_id;

        IF FOUND THEN
                t_entity_id = in_entity_id;
        ELSE
                INSERT INTO entity (name, entity_class, control_code,country_id)
                VALUES (in_legal_name, in_entity_class, t_control_code,in_country_id);
                t_entity_id := currval(&#39;entity_id_seq&#39;);
        END IF;

        UPDATE company
        SET legal_name = in_legal_name,
                tax_id = in_tax_id,
                sic_code = in_sic_code,
                sales_tax_id = in_sales_tax_id,
                license_number = in_license_number
        WHERE entity_id = t_entity_id;


        IF NOT FOUND THEN
                INSERT INTO company(entity_id, legal_name, tax_id, sic_code,
                                    sales_tax_id, license_number)
                VALUES (t_entity_id, in_legal_name, in_tax_id, in_sic_code,
                        in_sales_tax_id, in_license_number);

        END IF;
        SELECT * INTO t_retval FROM company WHERE entity_id = t_entity_id;
        RETURN t_retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function company_get_billing_info(in_id integer) -->
    <section id="public.function.company-get-billing-info-in-id-integer"
             xreflabel="()">
      <title id="public.function.company-get-billing-info-in-id-integer-title">
       company_get_billing_info(in_id integer)
      </title>
      <titleabbrev id="public.function.company-get-billing-info-in-id-integer-titleabbrev">
       company_get_billing_info(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>company_billing_info</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns billing information (billing name and address) for a given credit
account.
        <programlisting>
        select coalesce(eca.pay_to_name, c.legal_name), eca.meta_number,
                e.control_code, eca.cash_account_id, c.tax_id,
                a.line_one, a.line_two, a.line_three,
                a.city, a.state, a.mail_code, cc.name
        FROM (select legal_name, tax_id, entity_id
                FROM company
               UNION ALL
              SELECT last_name || &#39;, &#39; || first_name, null, entity_id
                FROM person) c
        JOIN entity e ON (c.entity_id = e.id)
        JOIN entity_credit_account eca ON (eca.entity_id = e.id)
        LEFT JOIN eca_to_location cl ON (eca.id = cl.credit_id)
        LEFT JOIN location a ON (a.id = cl.location_id)
        LEFT JOIN country cc ON (cc.id = a.country_id)
        WHERE eca.id = in_id AND (location_class = 1 or location_class is null);

</programlisting>
      </para>
    </section>

<!-- Function compound_array(anyarray) -->
    <section id="public.function.compound-array-anyarray"
             xreflabel="()">
      <title id="public.function.compound-array-anyarray-title">
       compound_array(anyarray)
      </title>
      <titleabbrev id="public.function.compound-array-anyarray-titleabbrev">
       compound_array(anyarray)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>INTERNAL</seg>
         <seg>anyarray</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an n dimensional array.

Example: SELECT as_array(ARRAY[id::text, class]) from contact_class

        <programlisting>aggregate_dummy</programlisting>
      </para>
    </section>

<!-- Function concat_colon(text) -->
    <section id="public.function.concat-colon-text"
             xreflabel="()">
      <title id="public.function.concat-colon-text-title">
       concat_colon(text)
      </title>
      <titleabbrev id="public.function.concat-colon-text-titleabbrev">
       concat_colon(text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>INTERNAL</seg>
         <seg>text</seg>
        </seglistitem>
       </segmentedlist>
 
        This is a sumple aggregate to return values from the database in a
colon-separated list.  Other programs probably should not rely on this since
it is primarily included for the chart view.
        <programlisting>aggregate_dummy</programlisting>
      </para>
    </section>

<!-- Function concat_colon(text, text) -->
    <section id="public.function.concat-colon-text-text"
             xreflabel="()">
      <title id="public.function.concat-colon-text-text-title">
       concat_colon(text, text)
      </title>
      <titleabbrev id="public.function.concat-colon-text-text-titleabbrev">
       concat_colon(text, text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function takes two arguments and creates a list out  of them.  It&apos;s useful
as an aggregate base (see aggregate concat_colon).  However this is a temporary
function only and should not be relied upon.
        <programlisting>
select CASE WHEN $1 IS NULL THEN $2 ELSE $1 || &#39;:&#39; || $2 END;
</programlisting>
      </para>
    </section>

<!-- Function contact__search(in_entity_class integer, in_contact text, in_contact_info text[], in_meta_number text, in_address text, in_city text, in_state text, in_mail_code text, in_country text, in_active_date_from date, in_active_date_to date, in_business_id integer, in_name_part text, in_control_code text, in_notes text, in_users boolean) -->
    <section id="public.function.contact-search-in-entity-class-integer-in-contact-text-in-contact-info-textARRAY-in-meta-number-text-in-address-text-in-city-text-in-state-text-in-mail-code-text-in-country-text-in-active-date-from-date-in-active-date-to-date-in-business-id-integer-in-name-part-text-in-control-code-text-in-notes-text-in-users-boolean"
             xreflabel="()">
      <title id="public.function.contact-search-in-entity-class-integer-in-contact-text-in-contact-info-textARRAY-in-meta-number-text-in-address-text-in-city-text-in-state-text-in-mail-code-text-in-country-text-in-active-date-from-date-in-active-date-to-date-in-business-id-integer-in-name-part-text-in-control-code-text-in-notes-text-in-users-boolean-title">
       contact__search(in_entity_class integer, in_contact text, in_contact_info text[], in_meta_number text, in_address text, in_city text, in_state text, in_mail_code text, in_country text, in_active_date_from date, in_active_date_to date, in_business_id integer, in_name_part text, in_control_code text, in_notes text, in_users boolean)
      </title>
      <titleabbrev id="public.function.contact-search-in-entity-class-integer-in-contact-text-in-contact-info-textARRAY-in-meta-number-text-in-address-text-in-city-text-in-state-text-in-mail-code-text-in-country-text-in-active-date-from-date-in-active-date-to-date-in-business-id-integer-in-name-part-text-in-control-code-text-in-notes-text-in-users-boolean-titleabbrev">
       contact__search(in_entity_class integer, in_contact text, in_contact_info text[], in_meta_number text, in_address text, in_city text, in_state text, in_mail_code text, in_country text, in_active_date_from date, in_active_date_to date, in_business_id integer, in_name_part text, in_control_code text, in_notes text, in_users boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF contact_search_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
                SELECT e.id, e.control_code, ec.id, ec.meta_number,
                        ec.description, ec.entity_class,
                        c.legal_name, c.sic_code, b.description , ec.curr::text
                FROM (select * from entity
                       where control_code like in_control_code || &#39;%&#39;
                      union
                      select * from entity where in_control_code is null) e
                JOIN (SELECT legal_name, sic_code, entity_id
                        FROM company
                       WHERE legal_name @@ plainto_tsquery(in_name_part)
                             OR legal_name ilike in_name_part || &#39;%&#39;
                      UNION ALL
                      SELECT legal_name, sic_code, entity_id
                        FROM company
                       WHERE in_name_part IS NULL
                      UNION ALL
                     SELECT coalesce(first_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(middle_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(last_name, &#39;&#39;), null, entity_id
                       FROM person
                      WHERE coalesce(first_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(middle_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(last_name, &#39;&#39;)
                             @@ plainto_tsquery(in_name_part)
                      UNION ALL
                     SELECT coalesce(first_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(middle_name, &#39;&#39;) || &#39; &#39;
                            || coalesce(last_name, &#39;&#39;), null, entity_id
                       FROM person
                       WHERE in_name_part IS NULL) c ON (e.id = c.entity_id)
                LEFT JOIN entity_credit_account ec ON (ec.entity_id = e.id)
                LEFT JOIN business b ON (ec.business_id = b.id)
                WHERE (in_entity_class is null
                        OR coalesce(ec.entity_class,e.entity_class) = in_entity_class)
                        AND (c.entity_id IN
                       (select entity_id
                          FROM entity_credit_account leca
                          JOIN eca_to_contact le2c ON leca.id = le2c.credit_id
                         WHERE contact ~*~ ANY(in_contact_info))
                      OR &#39;&#39; ILIKE ALL(in_contact_info)
                      OR in_contact_info IS NULL)

                        AND ((in_address IS NULL AND in_city IS NULL
                                        AND in_state IS NULL
                                        AND in_country IS NULL)
                                OR (c.entity_id IN
                                (select entity_id
                                   FROM entity_credit_account leca
                                   JOIN eca_to_location le2a
                                     ON leca.id = le2a.credit_id
                                   JOIN location ll ON le2a.location_id = ll.id
                                  WHERE (line_one @@ plainto_tsquery(in_address)
                                        OR
                                        line_two @@ plainto_tsquery(in_address)
                                        OR
                                        line_three @@ plainto_tsquery(in_address))
                                        AND city ILIKE
                                            &#39;%&#39; || coalesce(in_city, &#39;&#39;) || &#39;%&#39;
                                        AND state ILIKE
                                            &#39;%&#39; || coalesce(in_state, &#39;&#39;) || &#39;%&#39;
                                        AND mail_code ILIKE
                                            coalesce(in_mail_code, &#39;&#39;) || &#39;%&#39;
                                        AND country_id
                                            IN (SELECT id FROM country
                                                 WHERE name ilike in_country
                                                       OR short_name
                                                       ilike in_country))))
                        AND (ec.business_id =
                                coalesce(in_business_id, ec.business_id)
                                OR (ec.business_id IS NULL
                                        AND in_business_id IS NULL))
                        AND (ec.startdate &lt;= coalesce(in_active_date_to,
                                                ec.startdate)
                                OR (ec.startdate IS NULL))
                        AND (ec.enddate &gt;= coalesce(in_active_date_from, ec.enddate)
                                OR (ec.enddate IS NULL))
                        AND (ec.meta_number like in_meta_number || &#39;%&#39;
                             OR in_meta_number IS NULL)
                        AND (in_notes IS NULL OR e.id in (
                                     SELECT entity_id from entity_note
                                      WHERE note @@ plainto_tsquery(in_notes))
                                  OR ec.id IN (select ref_key FROM eca_note
                                     WHERE note @@ plainto_tsquery(in_notes)))
                        AND (in_users IS NULL OR in_users =
                             (exists (select 1 from users
                                       where entity_id = e.id)))
                        AND (in_contact IS NULL
                             OR e.id IN (select entity_id
                                           FROM entity_to_contact
                                          WHERE description
                                                @@ plainto_tsquery(in_contact))
                             OR ec.id IN (SELECT credit_id
                                            FROM eca_to_contact
                                           WHERE description
                                                 @@ plainto_tsquery(in_contact))
                       )
               ORDER BY legal_name;
</programlisting>
      </para>
    </section>

<!-- Function contact_class__list() -->
    <section id="public.function.contact-class-list"
             xreflabel="()">
      <title id="public.function.contact-class-list-title">
       contact_class__list()
      </title>
      <titleabbrev id="public.function.contact-class-list-titleabbrev">
       contact_class__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF contact_class</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of contact classes ordered by ID.
        <programlisting>
                SELECT * FROM contact_class ORDER BY id;
</programlisting>
      </para>
    </section>

<!-- Function cr_coa_to_account_save(in_accno text, in_description text) -->
    <section id="public.function.cr-coa-to-account-save-in-accno-text-in-description-text"
             xreflabel="()">
      <title id="public.function.cr-coa-to-account-save-in-accno-text-in-description-text-title">
       cr_coa_to_account_save(in_accno text, in_description text)
      </title>
      <titleabbrev id="public.function.cr-coa-to-account-save-in-accno-text-in-description-text-titleabbrev">
       cr_coa_to_account_save(in_accno text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
        Provides default rules for setting reconciliation labels.  Currently
saves a label of accno ||&apos;--&apos; || description.
        <programlisting>
    DECLARE
       v_chart_id int;
    BEGIN
        -- Check for existence of the account already
        PERFORM * FROM cr_coa_to_account cr
        JOIN account a on cr.chart_id = a.id
        WHERE accno = in_accno;

        IF NOT FOUND THEN
           -- This is a new account. Insert the relevant data.
           SELECT id INTO v_chart_id FROM chart WHERE accno = in_accno;
           INSERT INTO cr_coa_to_account (chart_id, account) VALUES (v_chart_id, in_accno||&#39;--&#39;||in_description);
        END IF;
        -- Already found, no need to do anything. =)
    END;
</programlisting>
      </para>
    </section>

<!-- Function cr_report_block_changing_approved() -->
    <section id="public.function.cr-report-block-changing-approved"
             xreflabel="()">
      <title id="public.function.cr-report-block-changing-approved-title">
       cr_report_block_changing_approved()
      </title>
      <titleabbrev id="public.function.cr-report-block-changing-approved-titleabbrev">
       cr_report_block_changing_approved()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
        This is a simple filter that prevents updating or deleting reconciliation
reports that have already been approved.  To purge old reconciliations you must
disable the block_change_when_approved trigger on cr_report.
        <programlisting>
BEGIN
   IF OLD.approved IS TRUE THEN
       RAISE EXCEPTION &#39;Report is approved.  Cannot change!&#39;;
   END IF;
   IF TG_OP = &#39;DELETE&#39; THEN
       RETURN OLD;
   ELSE
      RETURN NEW;
   END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function currency_get_exchangerate(in_currency bpchar, in_date date, in_account_class integer) -->
    <section id="public.function.currency-get-exchangerate-in-currency-bpchar-in-date-date-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.currency-get-exchangerate-in-currency-bpchar-in-date-date-in-account-class-integer-title">
       currency_get_exchangerate(in_currency bpchar, in_date date, in_account_class integer)
      </title>
      <titleabbrev id="public.function.currency-get-exchangerate-in-currency-bpchar-in-date-date-in-account-class-integer-titleabbrev">
       currency_get_exchangerate(in_currency bpchar, in_date date, in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        This function return the exchange rate of a given currency, date and exchange rate class (buy or sell). 
        <programlisting>
DECLARE
    out_exrate exchangerate.buy%TYPE;
    default_currency char(3);

    BEGIN
        SELECT * INTO default_currency  FROM defaults_get_defaultcurrency();
        IF default_currency = in_currency THEN
           RETURN 1;
        END IF;
        IF in_account_class = 2 THEN
          SELECT buy INTO out_exrate
          FROM exchangerate
          WHERE transdate = in_date AND curr = in_currency;
        ELSE
          SELECT sell INTO out_exrate
          FROM exchangerate
          WHERE transdate = in_date AND curr = in_currency;
        END IF;
        RETURN out_exrate;
    END;
</programlisting>
      </para>
    </section>

<!-- Function customer_location_save(in_entity_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer) -->
    <section id="public.function.customer-location-save-in-entity-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.customer-location-save-in-entity-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-title">
       customer_location_save(in_entity_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer)
      </title>
      <titleabbrev id="public.function.customer-location-save-in-entity-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-titleabbrev">
       customer_location_save(in_entity_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    BEGIN
    return _entity_location_save(
        in_entity_id, NULL,
        in_location_class, in_line_one, in_line_two, in_line_three,
        in_city, in_state, in_mail_code, in_country_id);
    END;

</programlisting>
      </para>
    </section>

<!-- Function date_get_all_years() -->
    <section id="public.function.date-get-all-years"
             xreflabel="()">
      <title id="public.function.date-get-all-years-title">
       date_get_all_years()
      </title>
      <titleabbrev id="public.function.date-get-all-years-titleabbrev">
       date_get_all_years()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF integer</seg>
        </seglistitem>
       </segmentedlist>
 
        This function return each year inside transdate in transactions.
Currently it uses a sparse index scan because the number of rows returned is
very small and the table can be very large.
        <programlisting>
WITH RECURSIVE max_dates AS (
    SELECT max(transdate) AS max_date
      FROM acc_trans
    WHERE transdate IS NOT NULL

 UNION ALL
    SELECT (SELECT max(transdate)
              FROM acc_trans
                   -- the index acc_trans_transdate_year_idx uses the
                   -- date_part function with the exact syntax and capitals
                   -- below; changing the &#39;YEAR&#39; capitals will stop the
                   -- query optimizer from using the index
             WHERE date_part(&#39;YEAR&#39;, transdate) &lt; date_part(&#39;YEAR&#39;, max_date))
      FROM max_dates
     WHERE max_date IS NOT NULL)

SELECT date_part(&#39;YEAR&#39;, max_date)::int
  FROM max_dates
 WHERE max_date IS NOT NULL;
</programlisting>
      </para>
    </section>

<!-- Function days_in_month(in_date date) -->
    <section id="public.function.days-in-month-in-date-date"
             xreflabel="()">
      <title id="public.function.days-in-month-in-date-date-title">
       days_in_month(in_date date)
      </title>
      <titleabbrev id="public.function.days-in-month-in-date-date-titleabbrev">
       days_in_month(in_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the number of days in the month that includes in_date.
        <programlisting>
SELECT (extract(DOM FROM date_trunc(&#39;month&#39;, $1)
                         + &#39;1 month - 1 second&#39;::interval)
      )::int;

</programlisting>
      </para>
    </section>

<!-- Function deduction__list_for_entity(in_entity_id integer) -->
    <section id="public.function.deduction-list-for-entity-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.deduction-list-for-entity-in-entity-id-integer-title">
       deduction__list_for_entity(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.deduction-list-for-entity-in-entity-id-integer-titleabbrev">
       deduction__list_for_entity(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_deduction</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_deduction WHERE entity_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function deduction__list_types(in_country_id integer) -->
    <section id="public.function.deduction-list-types-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.deduction-list-types-in-country-id-integer-title">
       deduction__list_types(in_country_id integer)
      </title>
      <titleabbrev id="public.function.deduction-list-types-in-country-id-integer-titleabbrev">
       deduction__list_types(in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_deduction_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_deduction_type where country_id = $1
</programlisting>
      </para>
    </section>

<!-- Function deduction__save(in_rate numeric, in_entity_id integer, in_type_id integer) -->
    <section id="public.function.deduction-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer"
             xreflabel="()">
      <title id="public.function.deduction-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer-title">
       deduction__save(in_rate numeric, in_entity_id integer, in_type_id integer)
      </title>
      <titleabbrev id="public.function.deduction-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer-titleabbrev">
       deduction__save(in_rate numeric, in_entity_id integer, in_type_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>payroll_deduction</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE return_ded payroll_deduction;
BEGIN

UPDATE payroll_deduction
   SET rate = in_rate
 WHERE entity_id = in_entity_id and in_type_id;


IF NOT FOUND THEN
    INSERT INTO payroll_deduction (entity_id, type_id, rate)
    VALUES (in_entity_id, in_type_id, in_rate);
END IF;

SELECT * INTO return_ded FROM payroll_deduction
             WHERE entity_id = in_entity_id and in_type_id;
RETURN return_ded;
END;
</programlisting>
      </para>
    </section>

<!-- Function defaults__get_contra_accounts(in_category bpchar) -->
    <section id="public.function.defaults-get-contra-accounts-in-category-bpchar"
             xreflabel="()">
      <title id="public.function.defaults-get-contra-accounts-in-category-bpchar-title">
       defaults__get_contra_accounts(in_category bpchar)
      </title>
      <titleabbrev id="public.function.defaults-get-contra-accounts-in-category-bpchar-titleabbrev">
       defaults__get_contra_accounts(in_category bpchar)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM account WHERE contra AND category = $1;
</programlisting>
      </para>
    </section>

<!-- Function defaults_get_defaultcurrency() -->
    <section id="public.function.defaults-get-defaultcurrency"
             xreflabel="()">
      <title id="public.function.defaults-get-defaultcurrency-title">
       defaults_get_defaultcurrency()
      </title>
      <titleabbrev id="public.function.defaults-get-defaultcurrency-titleabbrev">
       defaults_get_defaultcurrency()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>bpchar</seg>
        </seglistitem>
       </segmentedlist>
 
        This function return the default currency asigned by the program. 
        <programlisting>
           SELECT substr(value,1,3)
           FROM defaults
           WHERE setting_key = &#39;curr&#39;;
</programlisting>
      </para>
    </section>

<!-- Function del_recurring() -->
    <section id="public.function.del-recurring"
             xreflabel="()">
      <title id="public.function.del-recurring-title">
       del_recurring()
      </title>
      <titleabbrev id="public.function.del-recurring-titleabbrev">
       del_recurring()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
  DELETE FROM recurring WHERE id = old.id;
  DELETE FROM recurringemail WHERE id = old.id;
  DELETE FROM recurringprint WHERE id = old.id;
  RETURN NULL;
END;
</programlisting>
      </para>
    </section>

<!-- Function del_yearend() -->
    <section id="public.function.del-yearend"
             xreflabel="()">
      <title id="public.function.del-yearend-title">
       del_yearend()
      </title>
      <titleabbrev id="public.function.del-yearend-titleabbrev">
       del_yearend()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
begin
  delete from yearend where trans_id = old.id;
  return NULL;
end;
</programlisting>
      </para>
    </section>

<!-- Function draft__search(in_type text, in_with_accno text, in_from_date date, in_to_date date, in_amount_le numeric, in_amount_ge numeric) -->
    <section id="public.function.draft-search-in-type-text-in-with-accno-text-in-from-date-date-in-to-date-date-in-amount-le-numeric-in-amount-ge-numeric"
             xreflabel="()">
      <title id="public.function.draft-search-in-type-text-in-with-accno-text-in-from-date-date-in-to-date-date-in-amount-le-numeric-in-amount-ge-numeric-title">
       draft__search(in_type text, in_with_accno text, in_from_date date, in_to_date date, in_amount_le numeric, in_amount_ge numeric)
      </title>
      <titleabbrev id="public.function.draft-search-in-type-text-in-with-accno-text-in-from-date-date-in-to-date-date-in-amount-le-numeric-in-amount-ge-numeric-titleabbrev">
       draft__search(in_type text, in_with_accno text, in_from_date date, in_to_date date, in_amount_le numeric, in_amount_ge numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF draft_search_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Searches for drafts.  in_type may be any of &apos;ar&apos;, &apos;ap&apos;, or &apos;gl&apos;.
        <programlisting>
        SELECT id, transdate, invoice, reference, description,
               type, amount FROM (
            SELECT id, transdate, reference,
                   description, false as invoice,
                   (SELECT SUM(line.amount)
                      FROM acc_trans line
                     WHERE line.amount &gt; 0
                           and line.trans_id = gl.id) as amount,
                   &#39;gl&#39; as type
              from gl
             WHERE (lower(in_type) = &#39;gl&#39; or in_type is null)
                  AND NOT approved
                  AND NOT EXISTS (SELECT 1
                                    FROM voucher v
                                   WHERE v.trans_id = gl.id)
            UNION
            SELECT id, transdate, invnumber as reference,
                (SELECT name FROM eca__get_entity(entity_credit_account)),
                invoice, amount, &#39;ap&#39; as type
              FROM ap
             WHERE (lower(in_type) = &#39;ap&#39; or in_type is null)
                   AND NOT approved
                   AND NOT EXISTS (SELECT 1
                                     FROM voucher v
                                    WHERE v.trans_id = ap.id)
            UNION
            SELECT id, transdate, invnumber as reference,
                description, invoice, amount, &#39;ar&#39; as type
              FROM ar
             WHERE (lower(in_type) = &#39;ar&#39; or in_type is null)
                   AND NOT approved
                   AND NOT EXISTS (SELECT 1
                                     FROM voucher v
                                    WHERE v.trans_id = ar.id)) trans
        WHERE (in_from_date IS NULL or trans.transdate &gt;= in_from_date)
          AND (in_to_date IS NULL or trans.transdate &lt;= in_to_date)
          AND (in_with_accno IS NULL
               OR id IN (SELECT line.trans_id
                           FROM acc_trans line
                           JOIN account acc ON (line.chart_id = acc.id)
                          WHERE acc.accno = in_with_accno
                            AND NOT approved
                            AND (in_from_date IS NULL
                                 OR line.transdate &gt;= in_from_date)
                            AND (in_to_date IS NULL
                                 OR line.transdate &lt;= in_to_date)))
        ORDER BY trans.reference;
</programlisting>
      </para>
    </section>

<!-- Function draft_approve(in_id integer) -->
    <section id="public.function.draft-approve-in-id-integer"
             xreflabel="()">
      <title id="public.function.draft-approve-in-id-integer-title">
       draft_approve(in_id integer)
      </title>
      <titleabbrev id="public.function.draft-approve-in-id-integer-titleabbrev">
       draft_approve(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Posts draft to the books.  in_id is the id from the ar, ap, or gl table.
        <programlisting>
declare
        t_table text;
begin
        SELECT table_name into t_table FROM transactions where id = in_id;

        IF (t_table = &#39;ar&#39;) THEN
                PERFORM cogs__add_for_ar_line(id) FROM invoice
                  WHERE trans_id = in_id;
                UPDATE ar set approved = true where id = in_id;
        ELSIF (t_table = &#39;ap&#39;) THEN
                PERFORM cogs__add_for_ap_line(id) FROM invoice
                  WHERE trans_id = in_id;
                UPDATE ap set approved = true where id = in_id;
        ELSIF (t_table = &#39;gl&#39;) THEN
                UPDATE gl set approved = true where id = in_id;
        ELSE
                raise exception &#39;Invalid table % in draft_approve for transaction %&#39;, t_table, in_id;
        END IF;

        IF NOT FOUND THEN
                RETURN FALSE;
        END IF;

        UPDATE transactions
        SET approved_by =
                        (select entity_id FROM users
                        WHERE username = SESSION_USER),
                approved_at = now()
        WHERE id = in_id;

        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function draft_delete(in_id integer) -->
    <section id="public.function.draft-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.draft-delete-in-id-integer-title">
       draft_delete(in_id integer)
      </title>
      <titleabbrev id="public.function.draft-delete-in-id-integer-titleabbrev">
       draft_delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes the draft from the book.  Only will delete unapproved transactions.
Otherwise an exception is raised and the transaction terminated.
        <programlisting>
declare
        t_table text;
begin
        DELETE FROM ac_tax_form
        WHERE entry_id IN
                (SELECT entry_id FROM acc_trans WHERE trans_id = in_id);

        DELETE FROM acc_trans WHERE trans_id = in_id;
        SELECT lower(table_name) into t_table FROM transactions where id = in_id;

        IF t_table = &#39;ar&#39; THEN
                DELETE FROM ar WHERE id = in_id AND approved IS FALSE;
        ELSIF t_table = &#39;ap&#39; THEN
                DELETE FROM ap WHERE id = in_id AND approved IS FALSE;
        ELSIF t_table = &#39;gl&#39; THEN
                DELETE FROM gl WHERE id = in_id AND approved IS FALSE;
        ELSE
                raise exception &#39;Invalid table % in draft_delete for transaction %&#39;, t_table, in_id;
        END IF;
        IF NOT FOUND THEN
                RAISE EXCEPTION &#39;Invalid transaction id %&#39;, in_id;
        END IF;
        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function drop_custom_field(character varying, character varying) -->
    <section id="public.function.drop-custom-field-character-varying-character-varying"
             xreflabel="()">
      <title id="public.function.drop-custom-field-character-varying-character-varying-title">
       drop_custom_field(character varying, character varying)
      </title>
      <titleabbrev id="public.function.drop-custom-field-character-varying-character-varying-titleabbrev">
       drop_custom_field(character varying, character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
table_name ALIAS FOR $1;
custom_field_name ALIAS FOR $2;
BEGIN
        DELETE FROM custom_field_catalog
        WHERE field_name = custom_field_name AND
                table_id = (SELECT table_id FROM custom_table_catalog
                        WHERE extends = table_name);
        EXECUTE &#39;ALTER TABLE &#39; || quote_ident(&#39;custom_&#39; || table_name) ||
                &#39; DROP COLUMN &#39; || quote_ident(custom_field_name);
        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function eca__delete_contact(in_credit_id integer, in_class_id integer, in_contact text) -->
    <section id="public.function.eca-delete-contact-in-credit-id-integer-in-class-id-integer-in-contact-text"
             xreflabel="()">
      <title id="public.function.eca-delete-contact-in-credit-id-integer-in-class-id-integer-in-contact-text-title">
       eca__delete_contact(in_credit_id integer, in_class_id integer, in_contact text)
      </title>
      <titleabbrev id="public.function.eca-delete-contact-in-credit-id-integer-in-class-id-integer-in-contact-text-titleabbrev">
       eca__delete_contact(in_credit_id integer, in_class_id integer, in_contact text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if at least one record was deleted.  False if no records were
affected.
        <programlisting>
BEGIN

DELETE FROM eca_to_contact
 WHERE credit_id = in_credit_id and contact_class_id = in_class_id
       and contact= in_contact;
RETURN FOUND;

END;

</programlisting>
      </para>
    </section>

<!-- Function eca__delete_location(in_credit_id integer, in_id integer, in_location_class integer) -->
    <section id="public.function.eca-delete-location-in-credit-id-integer-in-id-integer-in-location-class-integer"
             xreflabel="()">
      <title id="public.function.eca-delete-location-in-credit-id-integer-in-id-integer-in-location-class-integer-title">
       eca__delete_location(in_credit_id integer, in_id integer, in_location_class integer)
      </title>
      <titleabbrev id="public.function.eca-delete-location-in-credit-id-integer-in-id-integer-in-location-class-integer-titleabbrev">
       eca__delete_location(in_credit_id integer, in_id integer, in_location_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes the record identified.  Returns true if successful, false if no record
found.
        <programlisting>
BEGIN

DELETE FROM eca_to_location
 WHERE credit_id = in_credit_id AND location_id = in_id
       AND location_class = in_location_class;

RETURN FOUND;

END;
</programlisting>
      </para>
    </section>

<!-- Function eca__delete_pricematrix(in_credit_id integer, in_entry_id integer) -->
    <section id="public.function.eca-delete-pricematrix-in-credit-id-integer-in-entry-id-integer"
             xreflabel="()">
      <title id="public.function.eca-delete-pricematrix-in-credit-id-integer-in-entry-id-integer-title">
       eca__delete_pricematrix(in_credit_id integer, in_entry_id integer)
      </title>
      <titleabbrev id="public.function.eca-delete-pricematrix-in-credit-id-integer-in-entry-id-integer-titleabbrev">
       eca__delete_pricematrix(in_credit_id integer, in_entry_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval bool;

BEGIN

retval := false;

DELETE FROM partsvendor
 WHERE entry_id = in_entry_id
       AND credit_id = in_credit_id;

retval := FOUND;

DELETE FROM partscustomer
 WHERE entry_id = in_entry_id
       AND credit_id = in_credit_id;

RETURN FOUND or retval;

END;
</programlisting>
      </para>
    </section>

<!-- Function eca__get_by_meta_number(in_meta_number text, in_entity_class integer) -->
    <section id="public.function.eca-get-by-meta-number-in-meta-number-text-in-entity-class-integer"
             xreflabel="()">
      <title id="public.function.eca-get-by-meta-number-in-meta-number-text-in-entity-class-integer-title">
       eca__get_by_meta_number(in_meta_number text, in_entity_class integer)
      </title>
      <titleabbrev id="public.function.eca-get-by-meta-number-in-meta-number-text-in-entity-class-integer-titleabbrev">
       eca__get_by_meta_number(in_meta_number text, in_entity_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>entity_credit_account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM entity_credit_account
 WHERE entity_class = $2 AND meta_number = $1;
</programlisting>
      </para>
    </section>

<!-- Function eca__get_entity(in_credit_id integer) -->
    <section id="public.function.eca-get-entity-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-get-entity-in-credit-id-integer-title">
       eca__get_entity(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-get-entity-in-credit-id-integer-titleabbrev">
       eca__get_entity(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of (only one) entity to which the entity credit account is
attached.
        <programlisting>

    SELECT entity.*
      FROM entity_credit_account
      JOIN entity ON entity_credit_account.entity_id = entity.id
     WHERE entity_credit_account.id = in_credit_id;

</programlisting>
      </para>
    </section>

<!-- Function eca__get_pricematrix(in_credit_id integer) -->
    <section id="public.function.eca-get-pricematrix-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-get-pricematrix-in-credit-id-integer-title">
       eca__get_pricematrix(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-get-pricematrix-in-credit-id-integer-titleabbrev">
       eca__get_pricematrix(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF eca__pricematrix</seg>
        </seglistitem>
       </segmentedlist>
 
        This returns the pricematrix for the customer or vendor
(entity_credit_account identified by in_id), orderd by partnumber, validfrom

        <programlisting>

SELECT pc.parts_id, p.partnumber, p.description, pc.credit_id, pc.pricebreak,
       pc.sellprice, NULL, NULL::int, NULL, pc.validfrom, pc.validto, pc.curr,
       pc.entry_id, pc.qty
  FROM partscustomer pc
  JOIN parts p on pc.parts_id = p.id
  JOIN entity_credit_account eca ON pc.credit_id = eca.id
 WHERE pc.credit_id = $1 AND eca.entity_class = 2
 UNION
SELECT pv.parts_id, p.partnumber, p.description, pv.credit_id, NULL, NULL,
       pv.lastcost, pv.leadtime::int, pv.partnumber, NULL, NULL, pv.curr,
       pv.entry_id, null
  FROM partsvendor pv
  JOIN parts p on pv.parts_id = p.id
  JOIN entity_credit_account eca ON pv.credit_id = eca.id
 WHERE pv.credit_id = $1 and eca.entity_class = 1
 ORDER BY partnumber, validfrom

</programlisting>
      </para>
    </section>

<!-- Function eca__get_pricematrix_by_pricegroup(in_credit_id integer) -->
    <section id="public.function.eca-get-pricematrix-by-pricegroup-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-get-pricematrix-by-pricegroup-in-credit-id-integer-title">
       eca__get_pricematrix_by_pricegroup(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-get-pricematrix-by-pricegroup-in-credit-id-integer-titleabbrev">
       eca__get_pricematrix_by_pricegroup(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF eca__pricematrix</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT pc.parts_id, p.partnumber, p.description, pc.credit_id, pc.pricebreak,
       pc.sellprice, NULL::numeric, NULL::int, NULL::text, pc.validfrom,
       pc.validto, pc.curr, pc.entry_id, pc.qty
  FROM partscustomer pc
  JOIN parts p on pc.parts_id = p.id
  JOIN entity_credit_account eca ON pc.pricegroup_id = eca.pricegroup_id
 WHERE eca.id = $1 AND eca.entity_class = 2
</programlisting>
      </para>
    </section>

<!-- Function eca__get_taxes(in_id integer) -->
    <section id="public.function.eca-get-taxes-in-id-integer"
             xreflabel="()">
      <title id="public.function.eca-get-taxes-in-id-integer-title">
       eca__get_taxes(in_id integer)
      </title>
      <titleabbrev id="public.function.eca-get-taxes-in-id-integer-titleabbrev">
       eca__get_taxes(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF eca_tax</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of taxable account id&apos;s.
        <programlisting>
select * from eca_tax where eca_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function eca__history(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean) -->
    <section id="public.function.eca-history-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean"
             xreflabel="()">
      <title id="public.function.eca-history-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean-title">
       eca__history(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean)
      </title>
      <titleabbrev id="public.function.eca-history-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean-titleabbrev">
       eca__history(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF eca_history_result</seg>
        </seglistitem>
       </segmentedlist>
 
       This produces a history detail report, i.e. a list of all products purchased by
a customer over a specific date range.

meta_number is an exact match, as are in_open and inc_closed.  All other fields
allow for partial matches.  NULL matches all values.
        <programlisting>
     WITH arap AS (
       select  invnumber, curr, ar.transdate, entity_credit_account, id,
                   person_id, notes
             FROM ar
             JOIN acc_trans ON ar.id  = acc_trans.trans_id
             JOIN account_link l ON acc_trans.chart_id = l.account_id
                  and l.description = &#39;AR&#39;
            where $16 = 2 and $13 = &#39;i&#39;
       GROUP BY 1, 2, 3, 4, 5, 6, 7
                  having (($17 and sum(acc_trans.amount) = 0)
                      or ($18 and 0 &lt;&gt; sum(acc_trans.amount)))
            UNION ALL
           select invnumber, curr, ap.transdate, entity_credit_account, id,
                  person_id, notes
             FROM ap
             JOIN acc_trans ON ap.id  = acc_trans.trans_id
             JOIN account_link l ON acc_trans.chart_id = l.account_id
                  and l.description = &#39;AP&#39;
            where $16 = 1 and $13 = &#39;i&#39;
       GROUP BY 1, 2, 3, 4, 5, 6, 7
                  having (($17 and sum(acc_trans.amount) = 0) or
                       ($18 and sum(acc_trans.amount) &lt;&gt; 0))
     )
     SELECT eca.id, e.name, eca.meta_number,
            a.id as invoice_id, a.invnumber, a.curr::text,
            p.id AS parts_id, p.partnumber,
            i.description,
            i.qty * case when eca.entity_class = 1 THEN -1 ELSE 1 END,
            i.unit::text, i.sellprice, i.discount,
            i.deliverydate,
            i.serialnumber,
            case when $16 = 1 then ex.buy else ex.sell end as exchange_rate,
            ee.id as salesperson_id,
            ep.last_name || &#39;, &#39; || ep.first_name as salesperson_name
     FROM (select * from entity_credit_account
            where meta_number = $2
           UNION
          select * from entity_credit_account WHERE $2 is null
          ) eca  -- broken into unions for performance
     join entity e on eca.entity_id = e.id
     JOIN (
           SELECT * FROM arap
           union
           select ordnumber, curr, transdate, entity_credit_account, id,
                  person_id, notes
           from oe
           where ($16= 1 and oe.oe_class_id = 2 and $13 = &#39;o&#39;
                  and quotation is not true)
                  and (($17 and not closed) or ($18 and closed))
           union
           select ordnumber, curr, transdate, entity_credit_account, id,
                  person_id, notes
           from oe
           where ($16= 2 and oe.oe_class_id = 1 and $13 = &#39;o&#39;
                  and quotation is not true)
                  and (($17 and not closed) or ($18 and closed))
           union
           select quonumber, curr, transdate, entity_credit_account, id,
                  person_id, notes
           from oe
           where($16= 1 and oe.oe_class_id = 4 and $13 = &#39;q&#39;
                and quotation is true)
                  and (($17 and not closed) or ($18 and closed))
           union
           select quonumber, curr, transdate, entity_credit_account, id,
                  person_id, notes
           from oe
           where($16= 2 and oe.oe_class_id = 4 and $13 = &#39;q&#39;
                 and quotation is true)
                  and (($17 and not closed) or ($18 and closed))
          ) a ON (a.entity_credit_account = eca.id) -- broken into unions
                                                    -- for performance
     JOIN ( select id, trans_id, parts_id, qty, description, unit, discount,
                   deliverydate, serialnumber, sellprice
             FROM  invoice where $13 = &#39;i&#39;
            union
            select id, trans_id, parts_id, qty, description, unit, discount,
                   reqdate, serialnumber, sellprice
             FROM orderitems where $13 &lt;&gt; &#39;i&#39;
          ) i on i.trans_id = a.id
     JOIN parts p ON (p.id = i.parts_id)
LEFT JOIN exchangerate ex ON (ex.transdate = a.transdate)
LEFT JOIN entity ee ON (a.person_id = ee.id)
LEFT JOIN person ep ON (ep.entity_id = ee.id)
    -- these filters don&#39;t perform as well on large databases
    WHERE (e.name ilike &#39;%&#39; || $1 || &#39;%&#39; or $1 is null)
          and ($3 is null or eca.id in
                 (select credit_id from eca_to_contact
                   where contact ilike &#39;%&#39; || $3 || &#39;%&#39;))
--          and (($4 is null and $5 is null and $6 is null and $7 is null)
--               or eca.id in
--                  (select credit_id from eca_to_location
--                    where location_id in
--                          (select id from location
--                            where ($4 is null or line_one ilike &#39;%&#39; || $4 || &#39;%&#39;
--                                   or line_two ilike &#39;%&#39; || $4 || &#39;%&#39;)
--                                  and ($5 is null or city
--                                                     ilike &#39;%&#39; || $5 || &#39;%&#39;)
--                                  and ($6 is null or state
--                                                    ilike &#39;%&#39; || $6 || &#39;%&#39;)
--                                  and ($7 is null or mail_code
--                                                    ilike &#39;%&#39; || $7 || &#39;%&#39;)
--                                  and ($10 is null or country_id = $10))
--                   )
--              )
--          and (a.transdate &gt;= $11 or $11 is null)
--          and (a.transdate &lt;= $12 or $12 is null)
--          and (eca.startdate &gt;= $14 or $14 is null)
--          and (eca.startdate &lt;= $15 or $15 is null)
--          and (a.notes @@ plainto_tsquery($9) or $9 is null)
 ORDER BY eca.meta_number, p.partnumber;
</programlisting>
      </para>
    </section>

<!-- Function eca__history_summary(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean) -->
    <section id="public.function.eca-history-summary-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean"
             xreflabel="()">
      <title id="public.function.eca-history-summary-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean-title">
       eca__history_summary(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean)
      </title>
      <titleabbrev id="public.function.eca-history-summary-in-name-part-text-in-meta-number-text-in-contact-info-text-in-address-line-text-in-city-text-in-state-text-in-zip-text-in-salesperson-text-in-notes-text-in-country-id-integer-in-from-date-date-in-to-date-date-in-type-bpchar-in-start-from-date-in-start-to-date-in-entity-class-integer-in-inc-open-boolean-in-inc-closed-boolean-titleabbrev">
       eca__history_summary(in_name_part text, in_meta_number text, in_contact_info text, in_address_line text, in_city text, in_state text, in_zip text, in_salesperson text, in_notes text, in_country_id integer, in_from_date date, in_to_date date, in_type bpchar, in_start_from date, in_start_to date, in_entity_class integer, in_inc_open boolean, in_inc_closed boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF eca_history_result</seg>
        </seglistitem>
       </segmentedlist>
 
       Creates a summary account (no quantities, just parts group by invoice).

meta_number must match exactly or be NULL.  inc_open and inc_closed are exact
matches too.  All other values specify ranges or may match partially.
        <programlisting>
SELECT id, name, meta_number, null::int, null::text, curr, parts_id, partnumber,
       description, sum(qty), unit, null::numeric, null::numeric, null::date,
       null::text, null::numeric,
       null::int, null::text
FROM   eca__history($1, $2, $3, $4, $5, $6, $7, $8, $9,
                   $10, $11, $12, $13, $14, $15, $16, $17, $18)
 group by id, name, meta_number, curr, parts_id, partnumber, description, unit,
          sellprice
 order by meta_number;
</programlisting>
      </para>
    </section>

<!-- Function eca__list_contacts(in_credit_id integer) -->
    <section id="public.function.eca-list-contacts-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-list-contacts-in-credit-id-integer-title">
       eca__list_contacts(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-list-contacts-in-credit-id-integer-titleabbrev">
       eca__list_contacts(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF contact_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of contact info attached to the entity credit account.
        <programlisting>
DECLARE out_row contact_list;
BEGIN
        FOR out_row IN
                SELECT cl.class, cl.id, c.description, c.contact
                FROM eca_to_contact c
                JOIN contact_class cl ON (c.contact_class_id = cl.id)
                WHERE credit_id = in_credit_id
        LOOP
                return next out_row;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function eca__list_locations(in_credit_id integer) -->
    <section id="public.function.eca-list-locations-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-list-locations-in-credit-id-integer-title">
       eca__list_locations(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-list-locations-in-credit-id-integer-titleabbrev">
       eca__list_locations(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF location_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of locations attached to the credit account.
        <programlisting>
                SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
                        l.state, l.mail_code, c.id, c.name, lc.id, lc.class
                FROM location l
                JOIN eca_to_location ctl ON (ctl.location_id = l.id)
                JOIN location_class lc ON (ctl.location_class = lc.id)
                JOIN country c ON (c.id = l.country_id)
                WHERE ctl.credit_id = in_credit_id
                ORDER BY lc.id, l.id, c.name
</programlisting>
      </para>
    </section>

<!-- Function eca__list_notes(in_credit_id integer) -->
    <section id="public.function.eca-list-notes-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.eca-list-notes-in-credit-id-integer-title">
       eca__list_notes(in_credit_id integer)
      </title>
      <titleabbrev id="public.function.eca-list-notes-in-credit-id-integer-titleabbrev">
       eca__list_notes(in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF note</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a list of notes attached to the entity credit account.
        <programlisting>
DECLARE out_row record;
        t_entity_id int;
BEGIN
        -- ALERT: security definer function.  Be extra careful about EXECUTE
        -- in here. --CT
        SELECT entity_id INTO t_entity_id
        FROM entity_credit_account
        WHERE id = in_credit_id;

        FOR out_row IN
                SELECT *
                FROM note
                WHERE (note_class = 3 and ref_key = in_credit_id) or
                        (note_class = 1 and ref_key = t_entity_id)
                ORDER BY created
        LOOP
                RETURN NEXT out_row;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function eca__location_save(in_credit_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_old_location_class integer) -->
    <section id="public.function.eca-location-save-in-credit-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-old-location-class-integer"
             xreflabel="()">
      <title id="public.function.eca-location-save-in-credit-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-old-location-class-integer-title">
       eca__location_save(in_credit_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_old_location_class integer)
      </title>
      <titleabbrev id="public.function.eca-location-save-in-credit-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-old-location-class-integer-titleabbrev">
       eca__location_save(in_credit_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_old_location_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves a location to an entity credit account. Returns id of saved record.
        <programlisting>

    DECLARE
        l_row location;
        l_id INT;
        l_orig_id INT;
    BEGIN

        UPDATE eca_to_location
           SET location_class = in_location_class
         WHERE credit_id = in_credit_id
           AND location_class = in_old_location_class
           AND location_id = in_id;

         IF FOUND THEN
            SELECT location_save(
                in_id,
                in_line_one,
                in_line_two,
                in_line_three,
                in_city,
                in_state,
                in_mail_code,
                in_country_id
            )
                INTO l_id;
        ELSE
            SELECT location_save(
                NULL,
                in_line_one,
                in_line_two,
                in_line_three,
                in_city,
                in_state,
                in_mail_code,
                in_country_id
            )
                INTO l_id;
            INSERT INTO eca_to_location
                        (credit_id, location_class, location_id)
                VALUES  (in_credit_id, in_location_class, l_id);

        END IF;

        RETURN l_id;
    END;

</programlisting>
      </para>
    </section>

<!-- Function eca__save(in_id integer, in_entity_class integer, in_entity_id integer, in_description text, in_discount numeric, in_taxincluded boolean, in_creditlimit numeric, in_discount_terms integer, in_terms integer, in_meta_number character varying, in_business_id integer, in_language_code character varying, in_pricegroup_id integer, in_curr bpchar, in_startdate date, in_enddate date, in_threshold numeric, in_ar_ap_account_id integer, in_cash_account_id integer, in_pay_to_name text, in_taxform_id integer, in_discount_account_id integer) -->
    <section id="public.function.eca-save-in-id-integer-in-entity-class-integer-in-entity-id-integer-in-description-text-in-discount-numeric-in-taxincluded-boolean-in-creditlimit-numeric-in-discount-terms-integer-in-terms-integer-in-meta-number-character-varying-in-business-id-integer-in-language-code-character-varying-in-pricegroup-id-integer-in-curr-bpchar-in-startdate-date-in-enddate-date-in-threshold-numeric-in-ar-ap-account-id-integer-in-cash-account-id-integer-in-pay-to-name-text-in-taxform-id-integer-in-discount-account-id-integer"
             xreflabel="()">
      <title id="public.function. ">
       eca__save(in_id integer, in_entity_class integer, in_entity_id integer, in_description text, in_discount numeric, in_taxincluded boolean, in_creditlimit numeric, in_discount_terms integer, in_terms integer, in_meta_number character varying, in_business_id integer, in_language_code character varying, in_pricegroup_id integer, in_curr bpchar, in_startdate date, in_enddate date, in_threshold numeric, in_ar_ap_account_id integer, in_cash_account_id integer, in_pay_to_name text, in_taxform_id integer, in_discount_account_id integer)
      </title>
      <titleabbrev id="public.function. ">
       eca__save(in_id integer, in_entity_class integer, in_entity_id integer, in_description text, in_discount numeric, in_taxincluded boolean, in_creditlimit numeric, in_discount_terms integer, in_terms integer, in_meta_number character varying, in_business_id integer, in_language_code character varying, in_pricegroup_id integer, in_curr bpchar, in_startdate date, in_enddate date, in_threshold numeric, in_ar_ap_account_id integer, in_cash_account_id integer, in_pay_to_name text, in_taxform_id integer, in_discount_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves an entity credit account.  Returns the id of the record saved.  
        <programlisting>

    DECLARE
        t_entity_class int;
        l_id int;
        t_meta_number text;
        t_mn_default_key text;
    BEGIN
        -- TODO:  Move to mapping table.
            IF in_entity_class = 1 THEN
               t_mn_default_key := &#39;vendornumber&#39;;
            ELSIF in_entity_class = 2 THEN
               t_mn_default_key := &#39;customernumber&#39;;
            END IF;
            IF in_meta_number IS NULL THEN
                t_meta_number := setting_increment(t_mn_default_key);
            ELSE
                t_meta_number := in_meta_number;
            END IF;
            update entity_credit_account SET
                discount = in_discount,
                taxincluded = in_taxincluded,
                creditlimit = in_creditlimit,
                description = in_description,
                terms = in_terms,
                ar_ap_account_id = in_ar_ap_account_id,
                cash_account_id = in_cash_account_id,
                discount_account_id = in_discount_account_id,
                meta_number = t_meta_number,
                business_id = in_business_id,
                language_code = in_language_code,
                pricegroup_id = in_pricegroup_id,
                curr = in_curr,
                startdate = in_startdate,
                enddate = in_enddate,
                threshold = in_threshold,
                discount_terms = in_discount_terms,
                pay_to_name = in_pay_to_name,
                taxform_id = in_taxform_id
            where id = in_id;

         IF FOUND THEN
            RETURN in_id;
         ELSE
            INSERT INTO entity_credit_account (
                entity_id,
                entity_class,
                discount,
                description,
                taxincluded,
                creditlimit,
                terms,
                meta_number,
                business_id,
                language_code,
                pricegroup_id,
                curr,
                startdate,
                enddate,
                discount_terms,
                threshold,
                ar_ap_account_id,
                pay_to_name,
                taxform_id,
                cash_account_id,
                discount_account_id
            )
            VALUES (
                in_entity_id,
                in_entity_class,
                in_discount,
                in_description,
                in_taxincluded,
                in_creditlimit,
                in_terms,
                t_meta_number,
                in_business_id,
                in_language_code,
                in_pricegroup_id,
                in_curr,
                in_startdate,
                in_enddate,
                in_discount_terms,
                in_threshold,
                in_ar_ap_account_id,
                in_pay_to_name,
                in_taxform_id,
                in_cash_account_id,
                in_discount_account_id
            );
            RETURN currval(&#39;entity_credit_account_id_seq&#39;);
       END IF;

    END;

</programlisting>
      </para>
    </section>

<!-- Function eca__save_contact(in_credit_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer) -->
    <section id="public.function.eca-save-contact-in-credit-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer"
             xreflabel="()">
      <title id="public.function.eca-save-contact-in-credit-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer-title">
       eca__save_contact(in_credit_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer)
      </title>
      <titleabbrev id="public.function.eca-save-contact-in-credit-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer-titleabbrev">
       eca__save_contact(in_credit_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>eca_to_contact</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves the contact record at the entity credit account level.  Returns 1.
        <programlisting>
DECLARE out_contact eca_to_contact;
BEGIN

    PERFORM *
       FROM eca_to_contact
      WHERE credit_id = in_credit_id
        AND contact_class_id = in_old_class_id
        AND contact = in_old_contact;

    IF FOUND THEN
        UPDATE eca_to_contact
           SET contact = in_contact,
               description = in_description,
               contact_class_id = in_class_id
         WHERE credit_id = in_credit_id
           AND contact_class_id = in_old_class_id
           AND contact = in_old_contact
        returning * INTO out_contact;
        return out_contact;
    END IF;
        INSERT INTO eca_to_contact(credit_id, contact_class_id,
                description, contact)
        VALUES (in_credit_id, in_class_id, in_description, in_contact)
        RETURNING * into out_contact;
        return out_contact;

END;
</programlisting>
      </para>
    </section>

<!-- Function eca__save_notes(in_credit_id integer, in_note text, in_subject text) -->
    <section id="public.function.eca-save-notes-in-credit-id-integer-in-note-text-in-subject-text"
             xreflabel="()">
      <title id="public.function.eca-save-notes-in-credit-id-integer-in-note-text-in-subject-text-title">
       eca__save_notes(in_credit_id integer, in_note text, in_subject text)
      </title>
      <titleabbrev id="public.function.eca-save-notes-in-credit-id-integer-in-note-text-in-subject-text-titleabbrev">
       eca__save_notes(in_credit_id integer, in_note text, in_subject text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>eca_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves an entity credit account-level note.  Such a note is valid for only one
credit account. Returns the id of the note.  
        <programlisting>
        -- TODO, change this to create vector too
        INSERT INTO eca_note (ref_key, note_class, note, vector, subject)
        VALUES (in_credit_id, 3, in_note, &#39;&#39;, in_subject)
        RETURNING *;

</programlisting>
      </para>
    </section>

<!-- Function eca__save_pricematrix(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer) -->
    <section id="public.function.eca-save-pricematrix-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer"
             xreflabel="()">
      <title id="public.function.eca-save-pricematrix-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer-title">
       eca__save_pricematrix(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer)
      </title>
      <titleabbrev id="public.function.eca-save-pricematrix-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer-titleabbrev">
       eca__save_pricematrix(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>eca__pricematrix</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
   retval eca__pricematrix;
   t_insert bool;

BEGIN

t_insert := false;

PERFORM * FROM entity_credit_account
  WHERE id = in_credit_id AND entity_class = 1;

IF FOUND THEN -- VENDOR
    UPDATE partsvendor
       SET lastcost = in_price,
           leadtime = in_lead_time,
           partnumber = in_partnumber,
           curr = in_curr
     WHERE credit_id = in_credit_id AND entry_id = in_entry_id;

    IF NOT FOUND THEN
        INSERT INTO partsvendor
               (parts_id, credit_id, lastcost, leadtime, partnumber, curr)
        VALUES (in_parts_id, in_credit_id, in_price, in_lead_time::int2,
               in_partnumber, in_curr);
    END IF;

    SELECT pv.parts_id, p.partnumber, p.description, pv.credit_id, NULL, NULL,
           pv.lastcost, pv.leadtime::int, pv.partnumber, NULL, NULL, pv.curr,
           pv.entry_id, null
      INTO retval
      FROM partsvendor pv
      JOIN parts p ON p.id = pv.parts_id
     WHERE parts_id = in_parts_id and credit_id = in_credit_id;

    RETURN retval;
END IF;

PERFORM * FROM entity_credit_account
  WHERE id = in_credit_id AND entity_class = 2;

IF FOUND THEN -- CUSTOMER
    UPDATE partscustomer
       SET pricebreak = in_pricebreak,
           sellprice  = in_price,
           validfrom  = in_validfrom,
           validto    = in_validto,
           qty        = in_qty,
           curr       = in_curr
     WHERE entry_id = in_entry_id and credit_id = in_credit_id;

    IF NOT FOUND THEN
        INSERT INTO partscustomer
               (parts_id, credit_id, sellprice, validfrom, validto, curr, qty)
        VALUES (in_parts_id, in_credit_id, in_price, in_validfrom, in_validto,
                in_curr, in_qty);

        t_insert := true;
    END IF;

    SELECT pc.parts_id, p.partnumber, p.description, pc.credit_id,
           pc.pricebreak, pc.sellprice, NULL, NULL, NULL, pc.validfrom,
           pc.validto, pc.curr, pc.entry_id, pc.qty
      INTO retval
      FROM partscustomer pc
      JOIN parts p on pc.parts_id = p.id
     WHERE entry_id = CASE WHEN t_insert
                           THEN currval(&#39;partscustomer_entry_id_seq&#39;)
                           ELSE in_entry_id
                      END;

    RETURN retval;

END IF;

RAISE EXCEPTION &#39;No valid entity credit account found&#39;;

END;
</programlisting>
      </para>
    </section>

<!-- Function eca__set_taxes(in_id integer, in_tax_ids integer[]) -->
    <section id="public.function.eca-set-taxes-in-id-integer-in-tax-ids-integerARRAY"
             xreflabel="()">
      <title id="public.function.eca-set-taxes-in-id-integer-in-tax-ids-integerARRAY-title">
       eca__set_taxes(in_id integer, in_tax_ids integer[])
      </title>
      <titleabbrev id="public.function.eca-set-taxes-in-id-integer-in-tax-ids-integerARRAY-titleabbrev">
       eca__set_taxes(in_id integer, in_tax_ids integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Sets the tax values for the customer or vendor.

The entity credit account must exist before calling this function, and must
have a type of either 1 or 2.

        <programlisting>
     DELETE FROM eca_tax WHERE eca_id = $1;
     INSERT INTO eca_tax (eca_id, chart_id)
     SELECT $1, tax_id
       FROM unnest($2) tax_id;
     SELECT TRUE;
</programlisting>
      </para>
    </section>

<!-- Function eca_bu_trigger() -->
    <section id="public.function.eca-bu-trigger"
             xreflabel="()">
      <title id="public.function.eca-bu-trigger-title">
       eca_bu_trigger()
      </title>
      <titleabbrev id="public.function.eca-bu-trigger-titleabbrev">
       eca_bu_trigger()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
  IF TG_OP = &#39;INSERT&#39; THEN
      INSERT INTO business_unit(class_id, control_code, description, credit_id)
      SELECT 7 - NEW.entity_class, NEW.meta_number,  e.name, NEW.id
             FROM entity e WHERE e.id = NEW.entity_id;
  ELSIF TG_OP = &#39;UPDATE&#39; THEN
      IF new.meta_number &lt;&gt; old.meta_number THEN
         UPDATE business_unit SET control_code = new.meta_number
          WHERE class_id = 7 - NEW.entity_class
                AND credit_id = new.id;
      END IF;
  ELSIF TG_OP = &#39;DELETE&#39;THEN
      DELETE FROM business_unit WHERE class_id = 7 - OLD.entity_class
                  AND credit_id = OLD.id;
      RETURN OLD;
  END IF;
  RETURN NEW;
END;
</programlisting>
      </para>
    </section>

<!-- Function employee__all_managers() -->
    <section id="public.function.employee-all-managers"
             xreflabel="()">
      <title id="public.function.employee-all-managers-title">
       employee__all_managers()
      </title>
      <titleabbrev id="public.function.employee-all-managers-titleabbrev">
       employee__all_managers()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF employee_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT p.entity_id, e.control_code, p.id, s.salutation, s.id,
          p.first_name, p.middle_name, p.last_name, ee.is_manager,
          ee.startdate, ee.enddate, ee.role, ee.ssn, ee.sales, ee.manager_id,
          mp.first_name, mp.last_name, ee.employeenumber, ee.dob, e.country_id
     FROM person p
     JOIN entity_employee ee on (ee.entity_id = p.entity_id)
     JOIN entity e ON (p.entity_id = e.id)
LEFT JOIN salutation s on (p.salutation_id = s.id)
LEFT JOIN person mp ON ee.manager_id = p.entity_id
    WHERE ee.is_manager
 ORDER BY ee.employeenumber;
</programlisting>
      </para>
    </section>

<!-- Function employee__all_salespeople() -->
    <section id="public.function.employee-all-salespeople"
             xreflabel="()">
      <title id="public.function.employee-all-salespeople-title">
       employee__all_salespeople()
      </title>
      <titleabbrev id="public.function.employee-all-salespeople-titleabbrev">
       employee__all_salespeople()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF employee_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT p.entity_id, e.control_code, p.id, s.salutation, s.id,
          p.first_name, p.middle_name, p.last_name, ee.is_manager,
          ee.startdate, ee.enddate, ee.role, ee.ssn, ee.sales, ee.manager_id,
          mp.first_name, mp.last_name, ee.employeenumber, ee.dob, e.country_id
     FROM person p
     JOIN entity_employee ee on (ee.entity_id = p.entity_id)
     JOIN entity e ON (p.entity_id = e.id)
LEFT JOIN salutation s on (p.salutation_id = s.id)
LEFT JOIN person mp ON ee.manager_id = p.entity_id
    WHERE ee.sales
 ORDER BY ee.employeenumber;
</programlisting>
      </para>
    </section>

<!-- Function employee__get(in_entity_id integer) -->
    <section id="public.function.employee-get-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.employee-get-in-entity-id-integer-title">
       employee__get(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.employee-get-in-entity-id-integer-titleabbrev">
       employee__get(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>employee_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an employee_result tuple with information specified by the entity_id.

        <programlisting>
   SELECT p.entity_id, e.control_code, p.id, s.salutation, s.id,
          p.first_name, p.middle_name, p.last_name, ee.is_manager,
          ee.startdate, ee.enddate, ee.role, ee.ssn, ee.sales, ee.manager_id,
          mp.first_name, mp.last_name, ee.employeenumber, ee.dob, e.country_id
     FROM person p
     JOIN entity_employee ee on (ee.entity_id = p.entity_id)
     JOIN entity e ON (p.entity_id = e.id)
LEFT JOIN salutation s on (p.salutation_id = s.id)
LEFT JOIN person mp ON ee.manager_id = p.entity_id
    WHERE p.entity_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function employee__get_user(in_entity_id integer) -->
    <section id="public.function.employee-get-user-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.employee-get-user-in-entity-id-integer-title">
       employee__get_user(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.employee-get-user-in-entity-id-integer-titleabbrev">
       employee__get_user(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>users</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns username, user_id, etc. information if the employee is a user.
        <programlisting>SELECT * FROM users WHERE entity_id = $1;</programlisting>
      </para>
    </section>

<!-- Function employee__list_managers(in_id integer) -->
    <section id="public.function.employee-list-managers-in-id-integer"
             xreflabel="()">
      <title id="public.function.employee-list-managers-in-id-integer-title">
       employee__list_managers(in_id integer)
      </title>
      <titleabbrev id="public.function.employee-list-managers-in-id-integer-titleabbrev">
       employee__list_managers(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF employees</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of managers, that is employees with the &apos;manager&apos; role set.
        <programlisting>
                SELECT
                    s.salutation,
                    p.first_name,
                    p.last_name,
                    ee.*
                FROM entity_employee ee
                JOIN entity e on e.id = ee.entity_id
                JOIN person p ON p.entity_id = e.id
                JOIN salutation s ON s.id = p.salutation_id
                WHERE ee.sales = &#39;t&#39;::bool AND ee.role=&#39;manager&#39;
                        AND ee.entity_id &lt;&gt; coalesce(in_id, -1)
                ORDER BY name
</programlisting>
      </para>
    </section>

<!-- Function employee__save(in_entity_id integer, in_start_date date, in_end_date date, in_dob date, in_role text, in_ssn text, in_sales boolean, in_manager_id integer, in_employeenumber text, in_is_manager boolean) -->
    <section id="public.function.employee-save-in-entity-id-integer-in-start-date-date-in-end-date-date-in-dob-date-in-role-text-in-ssn-text-in-sales-boolean-in-manager-id-integer-in-employeenumber-text-in-is-manager-boolean"
             xreflabel="()">
      <title id="public.function.employee-save-in-entity-id-integer-in-start-date-date-in-end-date-date-in-dob-date-in-role-text-in-ssn-text-in-sales-boolean-in-manager-id-integer-in-employeenumber-text-in-is-manager-boolean-title">
       employee__save(in_entity_id integer, in_start_date date, in_end_date date, in_dob date, in_role text, in_ssn text, in_sales boolean, in_manager_id integer, in_employeenumber text, in_is_manager boolean)
      </title>
      <titleabbrev id="public.function.employee-save-in-entity-id-integer-in-start-date-date-in-end-date-date-in-dob-date-in-role-text-in-ssn-text-in-sales-boolean-in-manager-id-integer-in-employeenumber-text-in-is-manager-boolean-titleabbrev">
       employee__save(in_entity_id integer, in_start_date date, in_end_date date, in_dob date, in_role text, in_ssn text, in_sales boolean, in_manager_id integer, in_employeenumber text, in_is_manager boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves an employeerecord with the specified information.
        <programlisting>
DECLARE out_id INT;
BEGIN
        UPDATE entity_employee
        SET startdate = coalesce(in_start_date, now()::date),
                enddate = in_end_date,
                dob = in_dob,
                role = in_role,
                ssn = in_ssn,
                manager_id = in_manager_id,
                employeenumber = in_employeenumber,
                is_manager = coalesce(in_is_manager, false),
                sales = in_sales
        WHERE entity_id = in_entity_id;

        out_id = in_entity_id;

        IF NOT FOUND THEN
                INSERT INTO entity_employee
                        (startdate, enddate, dob, role, ssn, manager_id,
                                employeenumber, entity_id, is_manager, sales)
                VALUES
                        (coalesce(in_start_date, now()::date), in_end_date,
                                in_dob, in_role, in_ssn,
                                in_manager_id, in_employeenumber,
                                in_entity_id, in_is_manager, in_sales);
                RETURN in_entity_id;
        END IF;
        RETURN out_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function employee__search(in_employeenumber text, in_startdate_from date, in_startdate_to date, in_first_name text, in_middle_name text, in_last_name text, in_notes text, in_is_user boolean) -->
    <section id="public.function.employee-search-in-employeenumber-text-in-startdate-from-date-in-startdate-to-date-in-first-name-text-in-middle-name-text-in-last-name-text-in-notes-text-in-is-user-boolean"
             xreflabel="()">
      <title id="public.function.employee-search-in-employeenumber-text-in-startdate-from-date-in-startdate-to-date-in-first-name-text-in-middle-name-text-in-last-name-text-in-notes-text-in-is-user-boolean-title">
       employee__search(in_employeenumber text, in_startdate_from date, in_startdate_to date, in_first_name text, in_middle_name text, in_last_name text, in_notes text, in_is_user boolean)
      </title>
      <titleabbrev id="public.function.employee-search-in-employeenumber-text-in-startdate-from-date-in-startdate-to-date-in-first-name-text-in-middle-name-text-in-last-name-text-in-notes-text-in-is-user-boolean-titleabbrev">
       employee__search(in_employeenumber text, in_startdate_from date, in_startdate_to date, in_first_name text, in_middle_name text, in_last_name text, in_notes text, in_is_user boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF employee_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of employee_result records matching the search criteria.

employeenumber is an exact match.
stardate_from and startdate_to specify the start dates for employee searches
All others are partial matches.

NULLs match all values.
        <programlisting>
SELECT p.entity_id, e.control_code, p.id, s.salutation, s.id,
          p.first_name, p.middle_name, p.last_name, ee.is_manager,
          ee.startdate, ee.enddate, ee.role, ee.ssn, ee.sales, ee.manager_id,
          mp.first_name, mp.last_name, ee.employeenumber, ee.dob, e.country_id
     FROM person p
     JOIN entity e ON p.entity_id = e.id
     JOIN entity_employee ee on (ee.entity_id = p.entity_id)
LEFT JOIN salutation s on (p.salutation_id = s.id)
LEFT JOIN person mp ON ee.manager_id = p.entity_id
    WHERE ($7 is null or p.entity_id in (select ref_key from entity_note
                                          WHERE note ilike &#39;%&#39; || $7 || &#39;%&#39;))
          and ($1 is null or $1 = ee.employeenumber)
          and ($2 is null or $2 &lt;= ee.startdate)
          and ($3 is null or $3 &gt;= ee.startdate)
          and ($4 is null or p.first_name ilike &#39;%&#39; || $4 || &#39;%&#39;)
          and ($5 is null or p.middle_name ilike &#39;%&#39; || $5 || &#39;%&#39;)
          and ($6 is null or p.last_name ilike &#39;%&#39; || $6 || &#39;%&#39;)
          and ($8 is null
               or $8 = (exists (select 1 from users where entity_id = e.id)));
</programlisting>
      </para>
    </section>

<!-- Function employee_search(in_startdatefrom date, in_startdateto date, in_name character varying, in_notes text, in_enddateto date, in_enddatefrom date, in_sales boolean) -->
    <section id="public.function.employee-search-in-startdatefrom-date-in-startdateto-date-in-name-character-varying-in-notes-text-in-enddateto-date-in-enddatefrom-date-in-sales-boolean"
             xreflabel="()">
      <title id="public.function.employee-search-in-startdatefrom-date-in-startdateto-date-in-name-character-varying-in-notes-text-in-enddateto-date-in-enddatefrom-date-in-sales-boolean-title">
       employee_search(in_startdatefrom date, in_startdateto date, in_name character varying, in_notes text, in_enddateto date, in_enddatefrom date, in_sales boolean)
      </title>
      <titleabbrev id="public.function.employee-search-in-startdatefrom-date-in-startdateto-date-in-name-character-varying-in-notes-text-in-enddateto-date-in-enddatefrom-date-in-sales-boolean-titleabbrev">
       employee_search(in_startdatefrom date, in_startdateto date, in_name character varying, in_notes text, in_enddateto date, in_enddatefrom date, in_sales boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF employee_search</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
                SELECT * FROM employee_search
                WHERE coalesce(startdate, &#39;infinity&#39;::timestamp)
                        &gt;= coalesce(in_startdateto, &#39;-infinity&#39;::timestamp)
                        AND coalesce(startdate, &#39;-infinity&#39;::timestamp) &lt;=
                                coalesce(in_startdatefrom,
                                                &#39;infinity&#39;::timestamp)
                        AND coalesce(enddate, &#39;-infinity&#39;::timestamp) &lt;=
                                coalesce(in_enddateto, &#39;infinity&#39;::timestamp)
                        AND coalesce(enddate, &#39;infinity&#39;::timestamp) &gt;=
                                coalesce(in_enddatefrom, &#39;-infinity&#39;::timestamp)
                        AND (name ~*~ in_name
                            OR note ~*~ in_notes)
                        AND (sales = &#39;t&#39; OR coalesce(in_sales, &#39;f&#39;) = &#39;f&#39;)
</programlisting>
      </para>
    </section>

<!-- Function entity__delete_bank_account(in_entity_id integer, in_id integer) -->
    <section id="public.function.entity-delete-bank-account-in-entity-id-integer-in-id-integer"
             xreflabel="()">
      <title id="public.function.entity-delete-bank-account-in-entity-id-integer-in-id-integer-title">
       entity__delete_bank_account(in_entity_id integer, in_id integer)
      </title>
      <titleabbrev id="public.function.entity-delete-bank-account-in-entity-id-integer-in-id-integer-titleabbrev">
       entity__delete_bank_account(in_entity_id integer, in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes the bank account identitied by in_id if it is attached to the entity
identified by entity_id.  Returns true if a record is deleted, false if not.
        <programlisting>
BEGIN

UPDATE entity_credit_account SET bank_account = NULL
 WHERE entity_id = in_entity_id AND bank_account = in_id;

DELETE FROM entity_bank_account
 WHERE id = in_id AND entity_id = in_entity_id;

RETURN FOUND;

END;
</programlisting>
      </para>
    </section>

<!-- Function entity__delete_contact(in_entity_id integer, in_class_id integer, in_contact text) -->
    <section id="public.function.entity-delete-contact-in-entity-id-integer-in-class-id-integer-in-contact-text"
             xreflabel="()">
      <title id="public.function.entity-delete-contact-in-entity-id-integer-in-class-id-integer-in-contact-text-title">
       entity__delete_contact(in_entity_id integer, in_class_id integer, in_contact text)
      </title>
      <titleabbrev id="public.function.entity-delete-contact-in-entity-id-integer-in-class-id-integer-in-contact-text-titleabbrev">
       entity__delete_contact(in_entity_id integer, in_class_id integer, in_contact text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if at least one record was deleted.  False if no records were
affected.
        <programlisting>
BEGIN

DELETE FROM entity_to_contact
 WHERE entity_id = in_entity_id
       and contact_class_id = in_class_id
       and contact= in_contact;
RETURN FOUND;

END;

</programlisting>
      </para>
    </section>

<!-- Function entity__delete_location(in_entity_id integer, in_id integer, in_location_class integer) -->
    <section id="public.function.entity-delete-location-in-entity-id-integer-in-id-integer-in-location-class-integer"
             xreflabel="()">
      <title id="public.function.entity-delete-location-in-entity-id-integer-in-id-integer-in-location-class-integer-title">
       entity__delete_location(in_entity_id integer, in_id integer, in_location_class integer)
      </title>
      <titleabbrev id="public.function.entity-delete-location-in-entity-id-integer-in-id-integer-in-location-class-integer-titleabbrev">
       entity__delete_location(in_entity_id integer, in_id integer, in_location_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes the record identified.  Returns true if successful, false if no record
found.
        <programlisting>
BEGIN

DELETE FROM entity_to_location
 WHERE entity_id = in_entity_id AND location_id = in_id
       AND location_class = in_location_class;

RETURN FOUND;

END;
</programlisting>
      </para>
    </section>

<!-- Function entity__get(in_entity_id integer) -->
    <section id="public.function.entity-get-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.entity-get-in-entity-id-integer-title">
       entity__get(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.entity-get-in-entity-id-integer-titleabbrev">
       entity__get(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of (only one) entity record with the entity id.
        <programlisting>
    SELECT * FROM entity WHERE id = in_entity_id;
</programlisting>
      </para>
    </section>

<!-- Function entity__get_bank_account(in_id integer) -->
    <section id="public.function.entity-get-bank-account-in-id-integer"
             xreflabel="()">
      <title id="public.function.entity-get-bank-account-in-id-integer-title">
       entity__get_bank_account(in_id integer)
      </title>
      <titleabbrev id="public.function.entity-get-bank-account-in-id-integer-titleabbrev">
       entity__get_bank_account(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>entity_bank_account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM  entity_bank_account WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function entity__list_bank_account(in_entity_id integer) -->
    <section id="public.function.entity-list-bank-account-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.entity-list-bank-account-in-entity-id-integer-title">
       entity__list_bank_account(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.entity-list-bank-account-in-entity-id-integer-titleabbrev">
       entity__list_bank_account(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_bank_account</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all bank accounts for the entity.
        <programlisting>
SELECT * from entity_bank_account where entity_id = in_entity_id;
</programlisting>
      </para>
    </section>

<!-- Function entity__list_classes() -->
    <section id="public.function.entity-list-classes"
             xreflabel="()">
      <title id="public.function.entity-list-classes-title">
       entity__list_classes()
      </title>
      <titleabbrev id="public.function.entity-list-classes-titleabbrev">
       entity__list_classes()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF entity_class</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of entity classes, ordered by assigned ids
        <programlisting>
DECLARE out_row entity_class;
BEGIN
        FOR out_row IN
                SELECT * FROM entity_class
                WHERE active and pg_has_role(SESSION_USER,
                                   lsmb__role_prefix()
                                   || &#39;contact_class_&#39;
                                   || lower(regexp_replace(class, &#39;( |\-)&#39;, &#39;_&#39;)),
                                   &#39;USAGE&#39;)
                ORDER BY id
        LOOP
                RETURN NEXT out_row;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function entity__list_contacts(in_entity_id integer) -->
    <section id="public.function.entity-list-contacts-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.entity-list-contacts-in-entity-id-integer-title">
       entity__list_contacts(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.entity-list-contacts-in-entity-id-integer-titleabbrev">
       entity__list_contacts(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF contact_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all contact info for the entity.
        <programlisting>
                SELECT cl.class, cl.id, c.description, c.contact
                FROM entity_to_contact c
                JOIN contact_class cl ON (c.contact_class_id = cl.id)
                WHERE c.entity_id = in_entity_id
</programlisting>
      </para>
    </section>

<!-- Function entity__list_credit(in_entity_id integer, in_entity_class integer) -->
    <section id="public.function.entity-list-credit-in-entity-id-integer-in-entity-class-integer"
             xreflabel="()">
      <title id="public.function.entity-list-credit-in-entity-id-integer-in-entity-class-integer-title">
       entity__list_credit(in_entity_id integer, in_entity_class integer)
      </title>
      <titleabbrev id="public.function.entity-list-credit-in-entity-id-integer-in-entity-class-integer-titleabbrev">
       entity__list_credit(in_entity_id integer, in_entity_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_credit_retrieve</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of entity credit account entries for the entity and of the
entity class.
        <programlisting>
                SELECT  ec.id, e.id, ec.entity_class, ec.discount,
                        ec.discount_terms,
                        ec.taxincluded, ec.creditlimit, ec.terms,
                        ec.meta_number, ec.description, ec.business_id,
                        ec.language_code,
                        ec.pricegroup_id, ec.curr::text, ec.startdate,
                        ec.enddate, ec.ar_ap_account_id, ec.cash_account_id,
                        ec.discount_account_id,
                        ec.threshold, e.control_code, ec.id, ec.pay_to_name,
                        ec.taxform_id
                FROM entity e
                JOIN entity_credit_account ec ON (e.id = ec.entity_id)
                WHERE e.id = in_entity_id
</programlisting>
      </para>
    </section>

<!-- Function entity__list_locations(in_entity_id integer) -->
    <section id="public.function.entity-list-locations-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.entity-list-locations-in-entity-id-integer-title">
       entity__list_locations(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.entity-list-locations-in-entity-id-integer-titleabbrev">
       entity__list_locations(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF location_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists all locations for an entity.
        <programlisting>
                SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
                        l.state, l.mail_code, c.id, c.name, lc.id, lc.class
                FROM location l
                JOIN entity_to_location ctl ON (ctl.location_id = l.id)
                JOIN location_class lc ON (ctl.location_class = lc.id)
                JOIN country c ON (c.id = l.country_id)
                WHERE ctl.entity_id = in_entity_id
                ORDER BY lc.id, l.id, c.name;
</programlisting>
      </para>
    </section>

<!-- Function entity__list_notes(in_entity_id integer) -->
    <section id="public.function.entity-list-notes-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.entity-list-notes-in-entity-id-integer-title">
       entity__list_notes(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.entity-list-notes-in-entity-id-integer-titleabbrev">
       entity__list_notes(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of notes (including content) attached to the entity.
        <programlisting>
                SELECT *
                FROM entity_note
                WHERE ref_key = in_entity_id
                ORDER BY created
</programlisting>
      </para>
    </section>

<!-- Function entity__location_save(in_entity_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_created date) -->
    <section id="public.function.entity-location-save-in-entity-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-created-date"
             xreflabel="()">
      <title id="public.function.entity-location-save-in-entity-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-created-date-title">
       entity__location_save(in_entity_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_created date)
      </title>
      <titleabbrev id="public.function.entity-location-save-in-entity-id-integer-in-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-city-text-in-state-text-in-mail-code-text-in-country-id-integer-in-created-date-titleabbrev">
       entity__location_save(in_entity_id integer, in_id integer, in_location_class integer, in_line_one text, in_line_two text, in_city text, in_state text, in_mail_code text, in_country_id integer, in_created date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves a location to a company.  Returns the location id.
        <programlisting>
    BEGIN
    return _entity_location_save(
        in_entity_id, in_id,
        in_location_class, in_line_one, in_line_two,
        &#39;&#39;, in_city , in_state, in_mail_code, in_country_id);
    END;

</programlisting>
      </para>
    </section>

<!-- Function entity__save_bank_account(in_entity_id integer, in_credit_id integer, in_bic text, in_iban text, in_remark text, in_bank_account_id integer) -->
    <section id="public.function.entity-save-bank-account-in-entity-id-integer-in-credit-id-integer-in-bic-text-in-iban-text-in-remark-text-in-bank-account-id-integer"
             xreflabel="()">
      <title id="public.function.entity-save-bank-account-in-entity-id-integer-in-credit-id-integer-in-bic-text-in-iban-text-in-remark-text-in-bank-account-id-integer-title">
       entity__save_bank_account(in_entity_id integer, in_credit_id integer, in_bic text, in_iban text, in_remark text, in_bank_account_id integer)
      </title>
      <titleabbrev id="public.function.entity-save-bank-account-in-entity-id-integer-in-credit-id-integer-in-bic-text-in-iban-text-in-remark-text-in-bank-account-id-integer-titleabbrev">
       entity__save_bank_account(in_entity_id integer, in_credit_id integer, in_bic text, in_iban text, in_remark text, in_bank_account_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>entity_bank_account</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves bank account to the credit account.
        <programlisting>
DECLARE out_bank entity_bank_account;
BEGIN
        UPDATE entity_bank_account
           SET bic = coalesce(in_bic,&#39;&#39;),
               iban = in_iban,
               remark = in_remark
         WHERE id = in_bank_account_id;

        IF FOUND THEN
             SELECT * INTO out_bank from entity_bank_account WHERE id = in_bank_account_id;

        ELSE
                INSERT INTO entity_bank_account(entity_id, bic, iban, remark)
                VALUES(in_entity_id, in_bic, in_iban, in_remark);
                SELECT * INTO out_bank from entity_bank_account WHERE id = CURRVAL(&#39;entity_bank_account_id_seq&#39;);
        END IF;

        IF in_credit_id IS NOT NULL THEN
                UPDATE entity_credit_account SET bank_account = out_bank.id
                WHERE id = in_credit_id;
        END IF;
        return out_bank;

END;
</programlisting>
      </para>
    </section>

<!-- Function entity__save_contact(in_entity_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer) -->
    <section id="public.function.entity-save-contact-in-entity-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer"
             xreflabel="()">
      <title id="public.function.entity-save-contact-in-entity-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer-title">
       entity__save_contact(in_entity_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer)
      </title>
      <titleabbrev id="public.function.entity-save-contact-in-entity-id-integer-in-class-id-integer-in-description-text-in-contact-text-in-old-contact-text-in-old-class-id-integer-titleabbrev">
       entity__save_contact(in_entity_id integer, in_class_id integer, in_description text, in_contact text, in_old_contact text, in_old_class_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>entity_to_contact</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves company contact information.  The return value is meaningless. 
        <programlisting>
        DELETE FROM entity_to_contact
         WHERE entity_id = in_entity_id AND contact = in_old_contact
               AND contact_class_id = in_old_class_id;

        INSERT INTO entity_to_contact
               (entity_id, contact_class_id, description, contact)
        VALUES (in_entity_id, in_class_id, in_description, in_contact)
         RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function entity__save_notes(in_entity_id integer, in_note text, in_subject text) -->
    <section id="public.function.entity-save-notes-in-entity-id-integer-in-note-text-in-subject-text"
             xreflabel="()">
      <title id="public.function.entity-save-notes-in-entity-id-integer-in-note-text-in-subject-text-title">
       entity__save_notes(in_entity_id integer, in_note text, in_subject text)
      </title>
      <titleabbrev id="public.function.entity-save-notes-in-entity-id-integer-in-note-text-in-subject-text-titleabbrev">
       entity__save_notes(in_entity_id integer, in_note text, in_subject text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>entity_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves an entity-level note.  Such a note is valid for all credit accounts
attached to that entity.  Returns the id of the note.  
        <programlisting>
        -- TODO, change this to create vector too
        INSERT INTO entity_note (ref_key, note_class, entity_id, note, vector, subject)
        VALUES (in_entity_id, 1, in_entity_id, in_note, &#39;&#39;, in_subject)
        RETURNING *;

</programlisting>
      </para>
    </section>

<!-- Function entity_credit__get(in_id integer) -->
    <section id="public.function.entity-credit-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.entity-credit-get-in-id-integer-title">
       entity_credit__get(in_id integer)
      </title>
      <titleabbrev id="public.function.entity-credit-get-in-id-integer-titleabbrev">
       entity_credit__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>entity_credit_account</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the entity credit account info.
        <programlisting>
SELECT * FROM entity_credit_account WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function entity_credit_get_id(in_entity_id integer, in_entity_class integer, in_meta_number text) -->
    <section id="public.function.entity-credit-get-id-in-entity-id-integer-in-entity-class-integer-in-meta-number-text"
             xreflabel="()">
      <title id="public.function.entity-credit-get-id-in-entity-id-integer-in-entity-class-integer-in-meta-number-text-title">
       entity_credit_get_id(in_entity_id integer, in_entity_class integer, in_meta_number text)
      </title>
      <titleabbrev id="public.function.entity-credit-get-id-in-entity-id-integer-in-entity-class-integer-in-meta-number-text-titleabbrev">
       entity_credit_get_id(in_entity_id integer, in_entity_class integer, in_meta_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an entity credit id, based on entity_id, entity_class,
and meta_number.  This is the preferred way to locate an account if all three of
these are known
        <programlisting>
        SELECT id FROM entity_credit_account
        WHERE entity_id = in_entity_id
                AND in_entity_class = entity_class
                AND in_meta_number = meta_number;

</programlisting>
      </para>
    </section>

<!-- Function entity_credit_get_id_by_meta_number(in_meta_number text, in_account_class integer) -->
    <section id="public.function.entity-credit-get-id-by-meta-number-in-meta-number-text-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.entity-credit-get-id-by-meta-number-in-meta-number-text-in-account-class-integer-title">
       entity_credit_get_id_by_meta_number(in_meta_number text, in_account_class integer)
      </title>
      <titleabbrev id="public.function.entity-credit-get-id-by-meta-number-in-meta-number-text-in-account-class-integer-titleabbrev">
       entity_credit_get_id_by_meta_number(in_meta_number text, in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the credit id from the meta_number and entity_class.
        <programlisting>
        SELECT id
        FROM entity_credit_account
        WHERE meta_number = in_meta_number
                AND entity_class = in_account_class;

</programlisting>
      </para>
    </section>

<!-- Function entity_save(in_entity_id integer, in_name text, in_entity_class integer) -->
    <section id="public.function.entity-save-in-entity-id-integer-in-name-text-in-entity-class-integer"
             xreflabel="()">
      <title id="public.function.entity-save-in-entity-id-integer-in-name-text-in-entity-class-integer-title">
       entity_save(in_entity_id integer, in_name text, in_entity_class integer)
      </title>
      <titleabbrev id="public.function.entity-save-in-entity-id-integer-in-name-text-in-entity-class-integer-titleabbrev">
       entity_save(in_entity_id integer, in_name text, in_entity_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Currently unused.  Left in because it is believed it may be helpful.

This saves an entity, with the control code being the next available via the
defaults table.
        <programlisting>

    DECLARE
        e entity;
        e_id int;

    BEGIN

        select * into e from entity where id = in_entity_id;

        update
            entity
        SET
            name = in_name,
            entity_class = in_entity_class
        WHERE
            id = in_entity_id;
        IF NOT FOUND THEN
            -- do the insert magic.
            e_id = nextval(&#39;entity_id_seq&#39;);
            insert into entity (id, name, entity_class) values
                (e_id,
                in_name,
                in_entity_class
                );
            return e_id;
        END IF;
        return in_entity_id;

    END;

</programlisting>
      </para>
    </section>

<!-- Function eoy__latest_checkpoint() -->
    <section id="public.function.eoy-latest-checkpoint"
             xreflabel="()">
      <title id="public.function.eoy-latest-checkpoint-title">
       eoy__latest_checkpoint()
      </title>
      <titleabbrev id="public.function.eoy-latest-checkpoint-titleabbrev">
       eoy__latest_checkpoint()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>account_checkpoint</seg>
        </seglistitem>
       </segmentedlist>
 
       
This returns a single checkpoint from the latest set.  Which account and info
is returned is non-determinative and so only the end date shoudl be relied on.

        <programlisting>
   SELECT * FROM account_checkpoint ORDER BY end_date DESC LIMIT 1;
</programlisting>
      </para>
    </section>

<!-- Function eoy__reopen_books_at(in_reopen_date date) -->
    <section id="public.function.eoy-reopen-books-at-in-reopen-date-date"
             xreflabel="()">
      <title id="public.function.eoy-reopen-books-at-in-reopen-date-date-title">
       eoy__reopen_books_at(in_reopen_date date)
      </title>
      <titleabbrev id="public.function.eoy-reopen-books-at-in-reopen-date-date-titleabbrev">
       eoy__reopen_books_at(in_reopen_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

  WITH eoy_dates AS (
      SELECT end_date
              FROM account_checkpoint
             WHERE end_date &gt;= $1
             GROUP BY end_date
    ORDER BY end_date DESC
    )
    SELECT eoy_reopen_books(end_date)
      FROM eoy_dates;

SELECT CASE WHEN (SELECT count(*) &gt; 0 from account_checkpoint
                   where end_date = $1 - 1)
            THEN true
            ELSE eoy_create_checkpoint($1 - 1) &gt; 0
       END;

</programlisting>
      </para>
    </section>

<!-- Function eoy_close_books(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer) -->
    <section id="public.function.eoy-close-books-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer"
             xreflabel="()">
      <title id="public.function.eoy-close-books-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer-title">
       eoy_close_books(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer)
      </title>
      <titleabbrev id="public.function.eoy-close-books-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer-titleabbrev">
       eoy_close_books(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Zeroes accounts and then creates a checkpoint. in_end_date is the date when
the books are to be closed, in_reference and in_description become the
reference and description of the gl transaction, and in_retention_acc_id is
the retained earnings account id.
        <programlisting>
BEGIN
        IF eoy_zero_accounts(in_end_date, in_reference, in_description, in_retention_acc_id) &gt; 0 THEN
                PERFORM eoy_create_checkpoint(in_end_date);
                RETURN TRUE;
        ELSE
                RETURN FALSE;
        END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function eoy_create_checkpoint(in_end_date date) -->
    <section id="public.function.eoy-create-checkpoint-in-end-date-date"
             xreflabel="()">
      <title id="public.function.eoy-create-checkpoint-in-end-date-date-title">
       eoy_create_checkpoint(in_end_date date)
      </title>
      <titleabbrev id="public.function.eoy-create-checkpoint-in-end-date-date-titleabbrev">
       eoy_create_checkpoint(in_end_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Creates checkpoints for each account at a specific date.  Books are considered
closed when they occur before the latest checkpoint timewise.  This means that
balances (and credit/debit amounts) can be calculated starting at a checkpoint
and moving forward (thus providing a mechanism for expunging old data while
keeping balances correct at some future point).
        <programlisting>
DECLARE ret_val int;
        approval_check int;
        cp_date        date;
BEGIN
        IF in_end_date &gt; now()::date THEN
                RAISE EXCEPTION &#39;Invalid date:  Must be earlier than present&#39;;
        END IF;

        SELECT count(*) into approval_check
        FROM acc_trans ac
        JOIN (
                select id, approved, transdate FROM ar UNION
                SELECT id, approved, transdate FROM gl UNION
                SELECT id, approved, transdate FROM ap
        ) gl ON (gl.id = ac.trans_id)
        WHERE (ac.approved IS NOT TRUE AND ac.transdate &lt;= in_end_date)
                OR (gl.approved IS NOT TRUE AND gl.transdate &lt;= in_end_date);

        if approval_check &gt; 0 THEN
                RAISE EXCEPTION &#39;Unapproved transactions in closed period&#39;;
        END IF;

        SELECT max(end_date) INTO cp_date FROM account_checkpoint WHERE
        end_date &lt; in_end_date;

        INSERT INTO
        account_checkpoint (end_date, account_id, amount, debits, credits)
    SELECT in_end_date, account.id,
            COALESCE(SUM (a.amount),0) + coalesce(MAX (cp.amount), 0),
            COALESCE(SUM (CASE WHEN (a.amount &lt; 0) THEN a.amount ELSE 0 END), 0) +
             COALESCE( MIN (cp.debits), 0),
            COALESCE(SUM (CASE WHEN (a.amount &gt; 0) THEN a.amount ELSE 0 END), 0) +
             COALESCE( MAX (cp.credits), 0)
        FROM
        (SELECT * FROM acc_trans WHERE transdate &lt;= in_end_date AND
         transdate &gt; COALESCE(cp_date, &#39;1200-01-01&#39;)) a
        FULL OUTER JOIN (
                select account_id, end_date, amount, debits, credits
                from account_checkpoint
                WHERE end_date = cp_date
                ) cp on (a.chart_id = cp.account_id)
        RIGHT JOIN account ON account.id = a.chart_id or account.id = cp.account_id
        group by COALESCE(a.chart_id, cp.account_id), account.id;

        SELECT count(*) INTO ret_val FROM account_checkpoint
        where end_date = in_end_date;

        return ret_val;
END;
</programlisting>
      </para>
    </section>

<!-- Function eoy_earnings_accounts() -->
    <section id="public.function.eoy-earnings-accounts"
             xreflabel="()">
      <title id="public.function.eoy-earnings-accounts-title">
       eoy_earnings_accounts()
      </title>
      <titleabbrev id="public.function.eoy-earnings-accounts-titleabbrev">
       eoy_earnings_accounts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists equity accounts for the retained earnings dropdown.
        <programlisting>
    SELECT *
      FROM account
     WHERE category = &#39;Q&#39;
     ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function eoy_reopen_books(in_end_date date) -->
    <section id="public.function.eoy-reopen-books-in-end-date-date"
             xreflabel="()">
      <title id="public.function.eoy-reopen-books-in-end-date-date-title">
       eoy_reopen_books(in_end_date date)
      </title>
      <titleabbrev id="public.function.eoy-reopen-books-in-end-date-date-titleabbrev">
       eoy_reopen_books(in_end_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Removes checkpoints and reverses yearend transactions on in_end_date
        <programlisting>
BEGIN
        PERFORM count(*) FROM account_checkpoint WHERE end_date = in_end_date;

        IF NOT FOUND THEN
                RETURN FALSE;
        END IF;

        DELETE FROM account_checkpoint WHERE end_date = in_end_date;

        PERFORM count(*) FROM yearend
        WHERE transdate = in_end_date and reversed is not true;

        IF FOUND THEN
                INSERT INTO gl (reference, description, approved)
                SELECT &#39;Reversing &#39; || reference, &#39;Reversing &#39; || description,
                        true
                FROM gl WHERE id = (select trans_id from yearend
                        where transdate = in_end_date and reversed is not true);

                INSERT INTO acc_trans (chart_id, amount, transdate, trans_id,
                        approved)
                SELECT chart_id, amount * -1, in_end_date, currval(&#39;id&#39;), true
                FROM acc_trans where trans_id = (select trans_id from yearend
                        where transdate = in_end_date and reversed is not true);

                UPDATE yearend SET reversed = true where transdate = in_end_date
                        and reversed is not true;
        END IF;

        DELETE FROM account_checkpoint WHERE end_date = in_end_date;
        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function eoy_zero_accounts(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer) -->
    <section id="public.function.eoy-zero-accounts-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer"
             xreflabel="()">
      <title id="public.function.eoy-zero-accounts-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer-title">
       eoy_zero_accounts(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer)
      </title>
      <titleabbrev id="public.function.eoy-zero-accounts-in-end-date-date-in-reference-text-in-description-text-in-retention-acc-id-integer-titleabbrev">
       eoy_zero_accounts(in_end_date date, in_reference text, in_description text, in_retention_acc_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Posts a transaction which zeroes the income and expense accounts, moving the
net balance there into a retained earnings account identified by
in_retention_acc_id.
        <programlisting>
DECLARE ret_val int;
BEGIN
        INSERT INTO gl (transdate, reference, description, approved)
        VALUES (in_end_date, in_reference, in_description, true);

        INSERT INTO yearend (trans_id, transdate) values (currval(&#39;id&#39;), in_end_date);
        INSERT INTO acc_trans (transdate, chart_id, trans_id, amount)
        SELECT in_end_date, a.chart_id, currval(&#39;id&#39;),
                (sum(a.amount) + coalesce(max(cp.amount), 0)) * -1
        FROM acc_trans a
        LEFT JOIN (
                select account_id, end_date, amount from account_checkpoint
                WHERE end_date = (select max(end_date) from account_checkpoint
                                where end_date &lt; in_end_date)
                ) cp on (a.chart_id = cp.account_id)
        JOIN account acc ON (acc.id = a.chart_id)
        WHERE a.transdate &lt;= in_end_date
                AND a.transdate &gt; coalesce(cp.end_date, a.transdate - 1)
                AND (acc.category IN (&#39;I&#39;, &#39;E&#39;)
                      OR acc.category = &#39;Q&#39; AND acc.is_temp)
        GROUP BY a.chart_id;

        INSERT INTO acc_trans (transdate, trans_id, chart_id, amount)
        SELECT in_end_date, currval(&#39;id&#39;), in_retention_acc_id,
                coalesce(sum(amount) * -1, 0)
        FROM acc_trans WHERE trans_id = currval(&#39;id&#39;);


        SELECT count(*) INTO ret_val from acc_trans
        where trans_id = currval(&#39;id&#39;);

        RETURN ret_val;
end;
</programlisting>
      </para>
    </section>

<!-- Function file__attach_to_eca(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-attach-to-eca-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-attach-to-eca-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-title">
       file__attach_to_eca(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-attach-to-eca-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__attach_to_eca(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Attaches or links a file to a good or service.  in_content OR id can be set.
Setting both raises an exception.

Note that currently links (setting id) is NOT supported because we dont have a
use case of linking files to entity credit accounts.
        <programlisting>
DECLARE retval file_base;
BEGIN
   IF in_id IS NOT NULL THEN
       IF in_content THEN
          RAISE EXCEPTION $e$Can&#39;t specify id and content in attachment$e$;--&#39;
       END IF;
       RAISE EXCEPTION &#39;links not implemented&#39;;
       RETURN retval;
   ELSE
       INSERT INTO file_eca
                   (content, mime_type_id, file_name, description, ref_key,
                   file_class, uploaded_by, uploaded_at)
            VALUES (in_content, in_mime_type_id, in_file_name, in_description,
                   in_ref_key, in_file_class, person__get_my_entity_id(),
                   now());
        SELECT * INTO retval FROM file_base
         where id = currval(&#39;file_base_id_seq&#39;);

        RETURN retval;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function file__attach_to_entity(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-attach-to-entity-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-attach-to-entity-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-title">
       file__attach_to_entity(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-attach-to-entity-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__attach_to_entity(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Attaches or links a file to a contact or entity.  in_content OR id can be
set. Setting both raises an exception.

Note that currently links (setting id) is NOT supported because we dont have a
use case of linking files to entities
        <programlisting>
DECLARE retval file_base;
BEGIN
   IF in_id IS NOT NULL THEN
       IF in_content THEN
          RAISE EXCEPTION $e$Can&#39;t specify id and content in attachment$e$;--&#39;
       END IF;
       RAISE EXCEPTION &#39;links not implemented&#39;;
       RETURN retval;
   ELSE
       INSERT INTO file_entity
                   (content, mime_type_id, file_name, description, ref_key,
                   file_class, uploaded_by, uploaded_at)
            VALUES (in_content, in_mime_type_id, in_file_name, in_description,
                   in_ref_key, in_file_class, person__get_my_entity_id(),
                   now());
        SELECT * INTO retval FROM file_base
         where id = currval(&#39;file_base_id_seq&#39;);

        RETURN retval;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function file__attach_to_order(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-attach-to-order-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-attach-to-order-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-title">
       file__attach_to_order(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-attach-to-order-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__attach_to_order(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Attaches or links a file to an order.  in_content OR id can be set.
Setting both raises an exception.
        <programlisting>
DECLARE retval file_base;
BEGIN
   IF in_id IS NOT NULL THEN
       IF in_content THEN
          RAISE EXCEPTION $e$Conflicting options file_id and content$e$;
       END IF;
       IF in_file_class = 1 THEN
           INSERT INTO file_tx_to_order
                  (file_id, source_class, ref_key, dest_class, attached_by,
                  attached_at)
           VALUES (in_id, 1, in_ref_key, 2, person__get_my_entity_id(), now());
       ELSIF in_file_class = 2 THEN
           INSERT INTO file_order_to_order
                  (file_id, source_class, ref_key, dest_class, attached_by,
                  attached_at)
           VALUES (in_id, 2, in_ref_key, 2, person__get_my_entity_id(), now());
       ELSE
           RAISE EXCEPTION $E$Invalid file class$E$;
       END IF;
       SELECT * INTO retval FROM file_base where id = in_id;
       RETURN retval;
   ELSE
       INSERT INTO file_order
                   (content, mime_type_id, file_name, description, ref_key,
                   file_class, uploaded_by, uploaded_at)
            VALUES (in_content, in_mime_type_id, in_file_name, in_description,
                   in_ref_key, in_file_class, person__get_my_entity_id(),
                   now());
        SELECT * INTO retval FROM file_base
         where id = currval(&#39;file_base_id_seq&#39;);

        RETURN retval;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function file__attach_to_part(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-attach-to-part-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-attach-to-part-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-title">
       file__attach_to_part(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-attach-to-part-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__attach_to_part(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Attaches or links a file to a good or service.  in_content OR id can be set.
Setting both raises an exception.

Note that currently links (setting id) is NOT supported because we dont have a
use case of linking files to parts
        <programlisting>
DECLARE retval file_base;
BEGIN
   IF in_id IS NOT NULL THEN
       IF in_content THEN
          RAISE EXCEPTION $e$Can&#39;t specify id and content in attachment$e$;--&#39;
       END IF;
       RAISE EXCEPTION &#39;links not implemented&#39;;
       RETURN retval;
   ELSE
       INSERT INTO file_part
                   (content, mime_type_id, file_name, description, ref_key,
                   file_class, uploaded_by, uploaded_at)
            VALUES (in_content, in_mime_type_id, in_file_name, in_description,
                   in_ref_key, in_file_class, person__get_my_entity_id(),
                   now());
        SELECT * INTO retval FROM file_base
         where id = currval(&#39;file_base_id_seq&#39;);

        RETURN retval;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function file__attach_to_tx(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-attach-to-tx-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-attach-to-tx-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-title">
       file__attach_to_tx(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-attach-to-tx-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-in-id-integer-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__attach_to_tx(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text, in_id integer, in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Attaches or links a file to a transaction.  in_content OR id can be set.
Setting both raises an exception.
        <programlisting>
DECLARE retval file_base;
BEGIN
   IF in_id IS NOT NULL THEN
       IF in_content THEN
          RAISE EXCEPTION $e$Can&#39;t specify id and content in attachment$e$;--&#39;
       END IF;
       INSERT INTO file_order_to_tx
              (file_id, source_class, ref_key, dest_class, attached_by,
              attached_at)
       VALUES (in_id, 2, in_ref_key, 1, person__get_my_entity_id(), now());

       SELECT * INTO retval FROM file_base where id = in_id;
       RETURN retval;
   ELSE
       INSERT INTO file_transaction
                   (content, mime_type_id, file_name, description, ref_key,
                   file_class, uploaded_by, uploaded_at)
            VALUES (in_content, in_mime_type_id, in_file_name, in_description,
                   in_ref_key, in_file_class, person__get_my_entity_id(),
                   now());
        SELECT * INTO retval FROM file_base
         where id = currval(&#39;file_base_id_seq&#39;);

        RETURN retval;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function file__get(in_id integer, in_file_class integer) -->
    <section id="public.function.file-get-in-id-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-get-in-id-integer-in-file-class-integer-title">
       file__get(in_id integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-get-in-id-integer-in-file-class-integer-titleabbrev">
       file__get(in_id integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves the file information specified including content.
        <programlisting>
SELECT * FROM file_base where id = $1 and file_class = $2;
</programlisting>
      </para>
    </section>

<!-- Function file__get_for_template(in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-get-for-template-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-get-for-template-in-ref-key-integer-in-file-class-integer-title">
       file__get_for_template(in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-get-for-template-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__get_for_template(in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF file_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT m.mime_type, CASE WHEN f.file_class = 3 THEN ref_key ||&#39;-&#39;|| f.file_name
                         ELSE f.file_name END,
       f.description, f.uploaded_by, e.name,
       f.uploaded_at, f.id, f.ref_key, f.file_class,  f.content
  FROM mime_type m
  JOIN file_base f ON f.mime_type_id = m.id
  JOIN entity e ON f.uploaded_by = e.id
 WHERE f.ref_key = $1 and f.file_class = $2
       AND m.invoice_include
       OR f.id IN (SELECT max(fb.id)
                   FROM file_base fb
                   JOIN mime_type m ON fb.mime_type_id = m.id
                        AND m.mime_type ilike &#39;image%&#39;
                   JOIN invoice i ON i.trans_id = $1
                        AND i.parts_id = fb.ref_key
                  WHERE fb.file_class = 3
               GROUP BY ref_key)
</programlisting>
      </para>
    </section>

<!-- Function file__get_mime_type(in_mime_type_id integer, in_mime_type_text text) -->
    <section id="public.function.file-get-mime-type-in-mime-type-id-integer-in-mime-type-text-text"
             xreflabel="()">
      <title id="public.function.file-get-mime-type-in-mime-type-id-integer-in-mime-type-text-text-title">
       file__get_mime_type(in_mime_type_id integer, in_mime_type_text text)
      </title>
      <titleabbrev id="public.function.file-get-mime-type-in-mime-type-id-integer-in-mime-type-text-text-titleabbrev">
       file__get_mime_type(in_mime_type_id integer, in_mime_type_text text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>mime_type</seg>
        </seglistitem>
       </segmentedlist>
 
       Retrieves mime type information associated with a file object.
        <programlisting>
select * from mime_type
 where ($1 IS NULL OR id = $1) AND ($2 IS NULL OR mime_type = $2);
</programlisting>
      </para>
    </section>

<!-- Function file__list_by(in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-list-by-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-list-by-in-ref-key-integer-in-file-class-integer-title">
       file__list_by(in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-list-by-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__list_by(in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF file_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of files attached to a database object.  No content is
retrieved.
        <programlisting>

SELECT m.mime_type, f.file_name, f.description, f.uploaded_by, e.name,
       f.uploaded_at, f.id, f.ref_key, f.file_class,
       case when m.mime_type = &#39;text/x-uri&#39; THEN f.content ELSE NULL END
  FROM mime_type m
  JOIN file_base f ON f.mime_type_id = m.id
  JOIN entity e ON f.uploaded_by = e.id
 WHERE f.ref_key = $1 and f.file_class = $2;

</programlisting>
      </para>
    </section>

<!-- Function file__list_links(in_ref_key integer, in_file_class integer) -->
    <section id="public.function.file-list-links-in-ref-key-integer-in-file-class-integer"
             xreflabel="()">
      <title id="public.function.file-list-links-in-ref-key-integer-in-file-class-integer-title">
       file__list_links(in_ref_key integer, in_file_class integer)
      </title>
      <titleabbrev id="public.function.file-list-links-in-ref-key-integer-in-file-class-integer-titleabbrev">
       file__list_links(in_ref_key integer, in_file_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF file_links</seg>
        </seglistitem>
       </segmentedlist>
 
        This function retrieves a list of file attachments on a specified object.
        <programlisting> select * from file_links where ref_key = $1 and dest_class = $2;
</programlisting>
      </para>
    </section>

<!-- Function file__save_incoming(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text) -->
    <section id="public.function.file-save-incoming-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text"
             xreflabel="()">
      <title id="public.function.file-save-incoming-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-title">
       file__save_incoming(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text)
      </title>
      <titleabbrev id="public.function.file-save-incoming-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-titleabbrev">
       file__save_incoming(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
       If the file_name is not unique, a unique constraint violation will be thrown.

        <programlisting>
INSERT INTO file_incoming(content, mime_type_id, file_name, description,
                          ref_key, file_class, uploaded_by)
SELECT $1, $2, $3, $4, 0, 7, entity_id
  FROM users where username = SESSION_USER
 RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function file__save_internal(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text) -->
    <section id="public.function.file-save-internal-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text"
             xreflabel="()">
      <title id="public.function.file-save-internal-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-title">
       file__save_internal(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text)
      </title>
      <titleabbrev id="public.function.file-save-internal-in-content-bytea-in-mime-type-id-integer-in-file-name-text-in-description-text-titleabbrev">
       file__save_internal(in_content bytea, in_mime_type_id integer, in_file_name text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>file_base</seg>
        </seglistitem>
       </segmentedlist>
 
       If the file_name is not unique, this will overwrite the previous stored file.

        <programlisting>
WITH up AS (
    UPDATE file_internal
       SET content = $1, uploaded_at = now(),
           uploaded_by = (select entity_id from users
                           where username = session_user)
     WHERE file_name = $3
 RETURNING true as found_it
)
INSERT INTO file_internal (content, mime_type_id, file_name, description,
                          ref_key, file_class, uploaded_by)
SELECT $1, $2, $3, $4, 0, 6, entity_id
  FROM users
 where username = SESSION_USER
       AND NOT EXISTS (select 1 from up)
RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function file_links_vrebuild() -->
    <section id="public.function.file-links-vrebuild"
             xreflabel="()">
      <title id="public.function.file-links-vrebuild-title">
       file_links_vrebuild()
      </title>
      <titleabbrev id="public.function.file-links-vrebuild-titleabbrev">
       file_links_vrebuild()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
   viewline file_view_catalog%rowtype;
   stmt text;
BEGIN
   stmt := &#39;&#39;;
   FOR viewline IN
       select * from file_view_catalog
   LOOP
       IF stmt = &#39;&#39; THEN
           stmt := &#39;SELECT * FROM &#39; || quote_ident(viewline.view_name) || &#39;
&#39;;
       ELSE
           stmt := stmt || &#39; UNION
SELECT * FROM &#39;|| quote_ident(viewline.view_name) || &#39;
&#39;;
       END IF;
   END LOOP;
   EXECUTE &#39;CREATE OR REPLACE VIEW file_links AS
&#39; || stmt;
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function form_check(in_session_id integer, in_form_id integer) -->
    <section id="public.function.form-check-in-session-id-integer-in-form-id-integer"
             xreflabel="()">
      <title id="public.function.form-check-in-session-id-integer-in-form-id-integer-title">
       form_check(in_session_id integer, in_form_id integer)
      </title>
      <titleabbrev id="public.function.form-check-in-session-id-integer-in-form-id-integer-titleabbrev">
       form_check(in_session_id integer, in_form_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        This checks to see if an open form (record in open_forms) exists with
the form_id and session_id provided.  Returns true if exists, false if not.
        <programlisting>
SELECT count(*) = 1
  FROM open_forms f
  JOIN &quot;session&quot; s USING (session_id)
  JOIN users u ON (s.users_id = u.id)
 WHERE f.session_id = $1 and f.id = $2 and u.username = SESSION_USER;
</programlisting>
      </para>
    </section>

<!-- Function form_close(in_session_id integer, in_form_id integer) -->
    <section id="public.function.form-close-in-session-id-integer-in-form-id-integer"
             xreflabel="()">
      <title id="public.function.form-close-in-session-id-integer-in-form-id-integer-title">
       form_close(in_session_id integer, in_form_id integer)
      </title>
      <titleabbrev id="public.function.form-close-in-session-id-integer-in-form-id-integer-titleabbrev">
       form_close(in_session_id integer, in_form_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Closes out the form by deleting it from the open_forms table.

Returns true if found, false if not.

        <programlisting>
DECLARE form_test bool;
BEGIN
        form_test := form_check(in_session_id, in_form_id);

        IF form_test IS TRUE THEN
                DELETE FROM open_forms
                WHERE session_id = in_session_id AND id = in_form_id;

                RETURN TRUE;

        ELSE
            RETURN FALSE;
        END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function form_open(in_session_id integer) -->
    <section id="public.function.form-open-in-session-id-integer"
             xreflabel="()">
      <title id="public.function.form-open-in-session-id-integer-title">
       form_open(in_session_id integer)
      </title>
      <titleabbrev id="public.function.form-open-in-session-id-integer-titleabbrev">
       form_open(in_session_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        This opens a form, and returns the id of the form opened.
        <programlisting>
DECLARE usertest bool;
    form_id int;
BEGIN
        SELECT count(*) = 1 INTO usertest FROM session
         WHERE session_id = in_session_id
               AND users_id IN (select id from users
                                WHERE username = SESSION_USER);

        IF usertest is not true THEN
            RAISE EXCEPTION &#39;Invalid session&#39;;
        END IF;

        INSERT INTO open_forms (session_id,last_used)
                        VALUES (in_session_id,now())
        RETURNING id INTO form_id;

        RETURN form_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function full_ilike_match(seek text, source text) -->
    <section id="public.function.full-ilike-match-seek-text-source-text"
             xreflabel="()">
      <title id="public.function.full-ilike-match-seek-text-source-text-title">
       full_ilike_match(seek text, source text)
      </title>
      <titleabbrev id="public.function.full-ilike-match-seek-text-source-text-titleabbrev">
       full_ilike_match(seek text, source text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
select seek ilike &#39;%&#39; || source || &#39;%&#39;;
</programlisting>
      </para>
    </section>

<!-- Function get_default_lang() -->
    <section id="public.function.get-default-lang"
             xreflabel="()">
      <title id="public.function.get-default-lang-title">
       get_default_lang()
      </title>
      <titleabbrev id="public.function.get-default-lang-titleabbrev">
       get_default_lang()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT coalesce((select description FROM language
    WHERE code = (SELECT substring(value, 1, 2) FROM defaults
                   WHERE setting_key = &#39;default_language&#39;)), &#39;english&#39;);
</programlisting>
      </para>
    </section>

<!-- Function get_fractional_month(in_date_first date, in_date_second date) -->
    <section id="public.function.get-fractional-month-in-date-first-date-in-date-second-date"
             xreflabel="()">
      <title id="public.function.get-fractional-month-in-date-first-date-in-date-second-date-title">
       get_fractional_month(in_date_first date, in_date_second date)
      </title>
      <titleabbrev id="public.function.get-fractional-month-in-date-first-date-in-date-second-date-titleabbrev">
       get_fractional_month(in_date_first date, in_date_second date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the number of months between two dates in numeric form.
        <programlisting>
SELECT CASE WHEN is_same_month($1, $2)
            THEN ($2 - $1)::numeric
                 / days_in_month($1)
            ELSE (get_fractional_month(
                   $1, (date_trunc(&#39;MONTH&#39;, $1)
                       + &#39;1 month - 1 second&#39;::interval)::date)
                 + get_fractional_month(date_trunc(&#39;MONTH&#39;, $2)::date, $2)
                 + (extract (&#39;YEAR&#39; from $2) - extract (&#39;YEAR&#39; from $1) * 12)
                 + extract (&#39;MONTH&#39; from $1) - extract (&#39;MONTH&#39; from $2)
                 - 1)::numeric
            END;
</programlisting>
      </para>
    </section>

<!-- Function get_fractional_year(in_date_from date, in_date_to date) -->
    <section id="public.function.get-fractional-year-in-date-from-date-in-date-to-date"
             xreflabel="()">
      <title id="public.function.get-fractional-year-in-date-from-date-in-date-to-date-title">
       get_fractional_year(in_date_from date, in_date_to date)
      </title>
      <titleabbrev id="public.function.get-fractional-year-in-date-from-date-in-date-to-date-titleabbrev">
       get_fractional_year(in_date_from date, in_date_to date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the decimal representation of the fractional year.
        <programlisting>
   select ($2 - $1
            - leap_days(next_leap_year_calc($1, false),
                       next_leap_year_calc($2, true)))
            /365::numeric;
</programlisting>
      </para>
    </section>

<!-- Function get_link_descriptions() -->
    <section id="public.function.get-link-descriptions"
             xreflabel="()">
      <title id="public.function.get-link-descriptions-title">
       get_link_descriptions()
      </title>
      <titleabbrev id="public.function.get-link-descriptions-titleabbrev">
       get_link_descriptions()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account_link_description</seg>
        </seglistitem>
       </segmentedlist>
 
        Gets a set of all valid account_link descriptions.
        <programlisting>
    SELECT * FROM account_link_description;
</programlisting>
      </para>
    </section>

<!-- Function gifi__list() -->
    <section id="public.function.gifi-list"
             xreflabel="()">
      <title id="public.function.gifi-list-title">
       gifi__list()
      </title>
      <titleabbrev id="public.function.gifi-list-titleabbrev">
       gifi__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF gifi</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM gifi ORDER BY accno;
</programlisting>
      </para>
    </section>

<!-- Function gl_audit_trail_append() -->
    <section id="public.function.gl-audit-trail-append"
             xreflabel="()">
      <title id="public.function.gl-audit-trail-append-title">
       gl_audit_trail_append()
      </title>
      <titleabbrev id="public.function.gl-audit-trail-append-titleabbrev">
       gl_audit_trail_append()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
        This provides centralized support for insertions into audittrail.

        <programlisting>
DECLARE
   t_reference text;
   t_row RECORD;
BEGIN

IF TG_OP = &#39;INSERT&#39; then
   t_row := NEW;
ELSE
   t_row := OLD;
END IF;

IF TG_RELNAME IN (&#39;ar&#39;, &#39;ap&#39;) THEN
    t_reference := t_row.invnumber;
ELSE
    t_reference := t_row.reference;
END IF;

INSERT INTO audittrail (trans_id,tablename,reference, action, person_id)
values (t_row.id,TG_RELNAME,t_reference, TG_OP, person__get_my_entity_id());

return null; -- AFTER TRIGGER ONLY, SAFE
END;
</programlisting>
      </para>
    </section>

<!-- Function goods__history(in_date_from date, in_date_to date, in_partnumber text, in_description text, in_serial_number text, in_inc_po boolean, in_inc_so boolean, in_inc_quo boolean, in_inc_rfq boolean, in_inc_is boolean, in_inc_ir boolean) -->
    <section id="public.function.goods-history-in-date-from-date-in-date-to-date-in-partnumber-text-in-description-text-in-serial-number-text-in-inc-po-boolean-in-inc-so-boolean-in-inc-quo-boolean-in-inc-rfq-boolean-in-inc-is-boolean-in-inc-ir-boolean"
             xreflabel="()">
      <title id="public.function.goods-history-in-date-from-date-in-date-to-date-in-partnumber-text-in-description-text-in-serial-number-text-in-inc-po-boolean-in-inc-so-boolean-in-inc-quo-boolean-in-inc-rfq-boolean-in-inc-is-boolean-in-inc-ir-boolean-title">
       goods__history(in_date_from date, in_date_to date, in_partnumber text, in_description text, in_serial_number text, in_inc_po boolean, in_inc_so boolean, in_inc_quo boolean, in_inc_rfq boolean, in_inc_is boolean, in_inc_ir boolean)
      </title>
      <titleabbrev id="public.function.goods-history-in-date-from-date-in-date-to-date-in-partnumber-text-in-description-text-in-serial-number-text-in-inc-po-boolean-in-inc-so-boolean-in-inc-quo-boolean-in-inc-rfq-boolean-in-inc-is-boolean-in-inc-ir-boolean-titleabbrev">
       goods__history(in_date_from date, in_date_to date, in_partnumber text, in_description text, in_serial_number text, in_inc_po boolean, in_inc_so boolean, in_inc_quo boolean, in_inc_rfq boolean, in_inc_is boolean, in_inc_ir boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF parts_history_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
  SELECT p.id, p.partnumber, o.transdate, p.description, p.bin,
         o.id as ord_id, o.ordnumber, o.oe_class, eca.meta_number::text, e.name,
         i.sellprice, i.qty, i.discount, i.serialnumber
    FROM parts p
    JOIN (select id, trans_id, parts_id, sellprice, qty, discount, serialnumber,
                 &#39;o&#39; as i_type
            FROM orderitems
           UNION
          SELECT id, trans_id, parts_id, sellprice, qty, discount, serialnumber,
                 &#39;i&#39; as i_type
            FROM invoice) i ON p.id = i.parts_id
    JOIN (select o.id, &#39;oe&#39; as o_table, ordnumber as ordnumber, c.oe_class,
                 o.oe_class_id, o.transdate, o.entity_credit_account
            FROM oe o
            JOIN oe_class c ON o.oe_class_id = c.id
           UNION
          SELECT id, &#39;ar&#39; as o_table, invnumber as ordnumber, &#39;is&#39; as oe_class,
                 null, transdate, entity_credit_account
            FROM ar
           UNION
          SELECT id, &#39;ap&#39; as o_table, invnumber as ordnumber, &#39;ir&#39; as oe_class,
                 null, transdate, entity_credit_account
            FROM ap) o ON o.id = i.trans_id
                          AND (o_table = &#39;oe&#39;) = (i_type = &#39;o&#39;)
    JOIN entity_credit_account eca ON o.entity_credit_account = eca.id
    JOIN entity e ON e.id = eca.entity_id
   WHERE (in_partnumber is null or p.partnumber like in_partnumber || &#39;%&#39;)
         AND (in_description IS NULL
              OR p.description @@ plainto_tsquery(in_description))
         AND (in_date_from is null or in_date_from &lt;= o.transdate)
         and (in_date_to is null or in_date_to &gt;= o.transdate)
         AND (in_inc_po is not true or o.oe_class = &#39;Purchase Order&#39;)
         AND (in_inc_so is not true or o.oe_class = &#39;Sales Order&#39;)
         AND (in_inc_quo is not true or o.oe_class = &#39;Quotation&#39;)
         AND (in_inc_rfq is not true or o.oe_class = &#39;RFQ&#39;)
         AND (in_inc_ir is not true or o.oe_class = &#39;ir&#39;)
         AND (in_inc_is is not true or o.oe_class = &#39;is&#39;)
ORDER BY o.transdate desc, o.id desc;
</programlisting>
      </para>
    </section>

<!-- Function goods__search(in_partnumber text, in_description text, in_partsgroup_id integer, in_serial_number text, in_make text, in_model text, in_drawing text, in_microfiche text, in_status text, in_date_from date, in_date_to date) -->
    <section id="public.function.goods-search-in-partnumber-text-in-description-text-in-partsgroup-id-integer-in-serial-number-text-in-make-text-in-model-text-in-drawing-text-in-microfiche-text-in-status-text-in-date-from-date-in-date-to-date"
             xreflabel="()">
      <title id="public.function.goods-search-in-partnumber-text-in-description-text-in-partsgroup-id-integer-in-serial-number-text-in-make-text-in-model-text-in-drawing-text-in-microfiche-text-in-status-text-in-date-from-date-in-date-to-date-title">
       goods__search(in_partnumber text, in_description text, in_partsgroup_id integer, in_serial_number text, in_make text, in_model text, in_drawing text, in_microfiche text, in_status text, in_date_from date, in_date_to date)
      </title>
      <titleabbrev id="public.function.goods-search-in-partnumber-text-in-description-text-in-partsgroup-id-integer-in-serial-number-text-in-make-text-in-model-text-in-drawing-text-in-microfiche-text-in-status-text-in-date-from-date-in-date-to-date-titleabbrev">
       goods__search(in_partnumber text, in_description text, in_partsgroup_id integer, in_serial_number text, in_make text, in_model text, in_drawing text, in_microfiche text, in_status text, in_date_from date, in_date_to date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF goods_search_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
       SELECT p.partnumber,
              p.id, p.description, p.onhand, p.unit::text, p.priceupdate,
              pg.partsgroup,
              p.listprice, p.sellprice, p.lastcost, p.avgcost,
              CASE WHEN p.lastcost = 0 THEN NULL
                   ELSE ((p.sellprice / p.lastcost) - 1) * 100
              END as markup,
              p.bin, p.rop, p.weight, p.notes, p.image, p.drawing, p.microfiche,
              m.make, m.model
         FROM parts p
    LEFT JOIN makemodel m ON m.parts_id = p.id
    LEFT JOIN partsgroup pg ON p.partsgroup_id = pg.id
        WHERE (in_partnumber is null or p.partnumber ilike in_partnumber || &#39;%&#39;)
              AND (in_description is null
                  or p.description @@ plainto_tsquery(in_description))
              AND (in_partsgroup_id is null
                  or p.partsgroup_id = in_partsgroup_id )
              AND (in_make is null or m.make ilike in_make || &#39;%&#39;)
              AND (in_model is null or m.model  ilike in_model || &#39;%&#39;)
              AND (in_drawing IS NULL OR p.drawing ilike in_drawing || &#39;%&#39;)
              AND (in_microfiche IS NULL
                  OR p.microfiche ilike in_microfiche || &#39;%&#39;)
              AND (in_serial_number IS NULL OR p.id IN
                      (select parts_id from invoice
                        where in_serial_number is not null
                              and serialnumber = in_serial_number))
              AND ((in_status = &#39;active&#39; and not p.obsolete)
                   OR (in_status = &#39;obsolete&#39; and p.obsolete)
                   OR (in_status = &#39;short&#39; and p.onhand &lt;= p.rop)
                   OR (in_status = &#39;unused&#39;
                      AND NOT EXISTS (select 1 FROM invoice
                                       WHERE parts_id = p.id
                                       UNION
                                      SELECT 1 FROM orderitems
                                       WHERE parts_id = p.id)));
</programlisting>
      </para>
    </section>

<!-- Function in_tree(in_node_id integer, in_search_array public.tree_record[]) -->
    <section id="public.function.in-tree-in-node-id-integer-in-search-array-public.tree-recordARRAY"
             xreflabel="()">
      <title id="public.function.in-tree-in-node-id-integer-in-search-array-public.tree-recordARRAY-title">
       in_tree(in_node_id integer, in_search_array public.tree_record[])
      </title>
      <titleabbrev id="public.function.in-tree-in-node-id-integer-in-search-array-public.tree-recordARRAY-titleabbrev">
       in_tree(in_node_id integer, in_search_array public.tree_record[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT CASE WHEN count(*) &gt; 0 THEN true ELSE false END
  FROM unnest($2) r
 WHERE t @&gt; array[$1];
</programlisting>
      </para>
    </section>

<!-- Function in_tree(in_node_id integer[], in_search_array public.tree_record[]) -->
    <section id="public.function.in-tree-in-node-id-integerARRAY-in-search-array-public.tree-recordARRAY"
             xreflabel="()">
      <title id="public.function.in-tree-in-node-id-integerARRAY-in-search-array-public.tree-recordARRAY-title">
       in_tree(in_node_id integer[], in_search_array public.tree_record[])
      </title>
      <titleabbrev id="public.function.in-tree-in-node-id-integerARRAY-in-search-array-public.tree-recordARRAY-titleabbrev">
       in_tree(in_node_id integer[], in_search_array public.tree_record[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT bool_and(in_tree(e, $2))
  FROM unnest($1) e;
</programlisting>
      </para>
    </section>

<!-- Function inventory__activity(in_from_date date, in_to_date date, in_partnumber text, in_description text) -->
    <section id="public.function.inventory-activity-in-from-date-date-in-to-date-date-in-partnumber-text-in-description-text"
             xreflabel="()">
      <title id="public.function.inventory-activity-in-from-date-date-in-to-date-date-in-partnumber-text-in-description-text-title">
       inventory__activity(in_from_date date, in_to_date date, in_partnumber text, in_description text)
      </title>
      <titleabbrev id="public.function.inventory-activity-in-from-date-date-in-to-date-date-in-partnumber-text-in-description-text-titleabbrev">
       inventory__activity(in_from_date date, in_to_date date, in_partnumber text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF inv_activity_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    SELECT p.id, p.description, p.partnumber,
           SUM(CASE WHEN transtype = &#39;ar&#39; THEN i.qty ELSE 0 END) AS sold,
           SUM(CASE WHEN transtype = &#39;ar&#39; THEN i.sellprice * i.qty ELSE 0 END)
           AS receivable,
           SUM(CASE WHEN transtype = &#39;ap&#39; THEN i.qty * -1 ELSE 0 END)
           AS payable,
           SUM(CASE WHEN transtype = &#39;ap&#39; THEN -1 * i.sellprice * i.qty ELSE 0
                END) AS expenses
      FROM invoice i
      JOIN parts p ON (i.parts_id = p.id)
      JOIN (select id, approved, transdate, &#39;ar&#39; as transtype FROM ar
             UNION
            SELECT id, approved, transdate, &#39;ap&#39; as transdate FROM ap) a
            ON (a.id = i.trans_id AND a.approved)
     WHERE ($1 IS NULL OR a.transdate &gt;= $1)
           AND ($2 IS NULL OR a.transdate &lt;= $2)
           AND ($3 IS NULL OR p.partnumber ilike $3 || &#39;%&#39;)
           AND ($4 IS NULL OR p.description @@ plainto_tsquery($4))
  GROUP BY p.id, p.description, p.partnumber
</programlisting>
      </para>
    </section>

<!-- Function inventory__get_item_by_id(in_id integer) -->
    <section id="public.function.inventory-get-item-by-id-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-get-item-by-id-in-id-integer-title">
       inventory__get_item_by_id(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-get-item-by-id-in-id-integer-titleabbrev">
       inventory__get_item_by_id(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM parts WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function inventory__get_item_by_partnumber(in_partnumber text) -->
    <section id="public.function.inventory-get-item-by-partnumber-in-partnumber-text"
             xreflabel="()">
      <title id="public.function.inventory-get-item-by-partnumber-in-partnumber-text-title">
       inventory__get_item_by_partnumber(in_partnumber text)
      </title>
      <titleabbrev id="public.function.inventory-get-item-by-partnumber-in-partnumber-text-titleabbrev">
       inventory__get_item_by_partnumber(in_partnumber text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM parts WHERE obsolete is not true AND partnumber = $1;
</programlisting>
      </para>
    </section>

<!-- Function inventory__search_part(in_parts_id integer, in_partnumber text, in_counted_date date) -->
    <section id="public.function.inventory-search-part-in-parts-id-integer-in-partnumber-text-in-counted-date-date"
             xreflabel="()">
      <title id="public.function.inventory-search-part-in-parts-id-integer-in-partnumber-text-in-counted-date-date-title">
       inventory__search_part(in_parts_id integer, in_partnumber text, in_counted_date date)
      </title>
      <titleabbrev id="public.function.inventory-search-part-in-parts-id-integer-in-partnumber-text-in-counted-date-date-titleabbrev">
       inventory__search_part(in_parts_id integer, in_partnumber text, in_counted_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>part_at_date</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH RECURSIVE assembly_comp (a_id, parts_id, qty) AS (
     SELECT id, parts_id, qty FROM assembly
      UNION ALL
     SELECT ac.a_id, a.parts_id, ac.qty * a.qty
       FROM assembly a JOIN assembly_comp ac ON a.parts_id = ac.parts_id
)
     SELECT p.id, p.partnumber,
            sum((coalesce(i.qty, 0) + coalesce(oi.qty, 0)) * a.qty )
       FROM parts p
  LEFT JOIN assembly_comp a ON a.a_id = p.id
  LEFT JOIN invoice_sum i ON i.parts_id = p.id OR a.parts_id = i.parts_id
  LEFT JOIN order_sum oi ON oi.parts_id = p.id OR a.parts_id = i.parts_id
      WHERE p.id = $1 OR p.partnumber = $2
            OR (p.id IN (select parts_id FROM makemodel WHERE barcode = $2)
               AND NOT EXISTS (select id from parts
                                where partnumber = $2 AND NOT obsolete
            ))
            and (i.transdate is null or i.transdate &lt;= $3)
            AND (oi.transdate IS NULL OR oi.transdate &lt;= $3)
   GROUP BY p.id, p.partnumber;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adj__details(in_id integer) -->
    <section id="public.function.inventory-adj-details-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adj-details-in-id-integer-title">
       inventory_adj__details(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adj-details-in-id-integer-titleabbrev">
       inventory_adj__details(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF inventory_adjustment_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

   SELECT l.parts_id, p.partnumber, p.description, l.counted, l.expected,
          l.counted - l.expected, p.sellprice, p.lastcost
     FROM inventory_report_line l
     JOIN parts p ON l.parts_id = p.id
    WHERE l.adjust_id = $1;

</programlisting>
      </para>
    </section>

<!-- Function inventory_adj__get(in_id integer) -->
    <section id="public.function.inventory-adj-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adj-get-in-id-integer-title">
       inventory_adj__get(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adj-get-in-id-integer-titleabbrev">
       inventory_adj__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_adjustment_info</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

   SELECT r.id, r.transdate, r.source, r.ar_trans_id, r.ap_trans_id,
          ar.invnumber, ap.invnumber
     FROM inventory_report r
     JOIN inventory_report_line l ON l.adjust_id = r.id
LEFT JOIN ar ON ar.id = r.ar_trans_id
LEFT JOIN ap ON ap.id = r.ap_trans_id
    WHERE r.id = $1;

</programlisting>
      </para>
    </section>

<!-- Function inventory_adj__search(in_from_date date, in_to_date date, in_partnumber text, in_source text) -->
    <section id="public.function.inventory-adj-search-in-from-date-date-in-to-date-date-in-partnumber-text-in-source-text"
             xreflabel="()">
      <title id="public.function.inventory-adj-search-in-from-date-date-in-to-date-date-in-partnumber-text-in-source-text-title">
       inventory_adj__search(in_from_date date, in_to_date date, in_partnumber text, in_source text)
      </title>
      <titleabbrev id="public.function.inventory-adj-search-in-from-date-date-in-to-date-date-in-partnumber-text-in-source-text-titleabbrev">
       inventory_adj__search(in_from_date date, in_to_date date, in_partnumber text, in_source text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF inventory_adjustment_info</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

   SELECT r.id, r.transdate, r.source, r.ar_trans_id, r.ap_trans_id,
          ar.invnumber, ap.invnumber
     FROM inventory_report r
     JOIN inventory_report_line l ON l.adjust_id = r.id
     JOIN parts p ON l.parts_id = p.id
LEFT JOIN ar ON ar.id = r.ar_trans_id
LEFT JOIN ap ON ap.id = r.ap_trans_id
    WHERE ($1 is null or $1 &lt;= r.transdate) AND
          ($2 is null OR $2 &gt;= r.transdate) AND
          ($3 IS NULL OR plainto_tsquery($3) @@ tsvector(p.partnumber)) AND
          ($4 IS NULL OR source LIKE $4 || &#39;%&#39;)
 GROUP BY r.id, r.transdate, r.source, r.ar_trans_id, r.ap_trans_id,
          ar.invnumber, ap.invnumber
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__approve(in_id integer) -->
    <section id="public.function.inventory-adjust-approve-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adjust-approve-in-id-integer-title">
       inventory_adjust__approve(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adjust-approve-in-id-integer-titleabbrev">
       inventory_adjust__approve(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>inventory_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE inv inventory_report;
        t_ar ar;
        t_ap ap;
BEGIN

SELECT * INTO inv FROM inventory_report where id = in_id;

INSERT INTO ar (entity_credit_account, invnumber, invoice, approved,
                amount, netamount, transdate)
VALUES (setting__get(&#39;inventory_ar_eca&#39;), setting_increment(&#39;sinumber&#39;),
        &#39;t&#39;, &#39;f&#39;, 0, 0, inv.transdate);

SELECT * INTO t_ar FROM ar WHERE id = currval(&#39;id&#39;);

UPDATE inventory_report
   set ar_trans_id = t_ar.id,
       ar_invnumber = t_ar.invnumber
 WHERE id = in_id;

INSERT INTO invoice (trans_id, parts_id, description, qty, sellprice, precision,
                    discount)
SELECT t_ar.id, p.id, p.description, l.variance * -1, p.sellprice, 3, 1
  FROM parts p
  JOIN inventory_report_line l ON p.id = l.parts_id
 WHERE l.adjust_id = in_id;

INSERT INTO ap (entity_credit_account, invnumber, invoice, approved, amount,
                netamount, transdate)
SELECT setting__get(&#39;inventory_ap_eca&#39;), setting_increment(&#39;vinumber&#39;),
       &#39;t&#39;, &#39;f&#39;, sum(l.variance * p.sellprice), sum(l.variance * p.sellprice),
       inv.transdate
  FROM parts p
  JOIN inventory_report_line l ON p.id = l.parts_id
 WHERE l.adjust_id = in_id;

SELECT * INTO t_ap FROM ap WHERE id = currval(&#39;id&#39;);

UPDATE inventory_report
   set ap_trans_id = t_ap.id,
       ap_invnumber = t_ap.invnumber
 WHERE id = in_id;

INSERT INTO invoice (trans_id, parts_id, description, qty, sellprice, precision,
                    discount, transdate)
SELECT t_ap.id, p.id, p.description, l.variance * -1, p.sellprice, 3, 0
  FROM parts p
  JOIN inventory_report_line l ON p.id = l.parts_id
 WHERE l.adjust_id = in_id;

INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, approved)
SELECT t_ap.id, p.expense_accno_id, sum(l.variance * -1 * p.lastcost),
       inv.transdate, true
  FROM parts p
  JOIN inventory_report_line l ON p.id = l.parts_id
 WHERE l.adjust_id = in_id
 GROUP BY p.expense_accno_id
 UNION
SELECT t_ap.id, eca.ar_ap_accno_id, sum(l.variance * -1 * p.lastcost),
       inv.transdate, true
  FROM parts p
  JOIN inventory_report_line l ON p.id = l.parts_id
  JOIN entity_credit_account eca on eca_id = t_ap.entity_credit_account
 WHERE l.adjust_id = in_id
 GROUP BY eca.ar_ap_accno_id;

SELECT * INTO inv FROM inventory_report where id = in_id;

RETURN inv;

END;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__delete(in_id integer) -->
    <section id="public.function.inventory-adjust-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adjust-delete-in-id-integer-title">
       inventory_adjust__delete(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adjust-delete-in-id-integer-titleabbrev">
       inventory_adjust__delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE inv inventory_report;
BEGIN
SELECT * INTO inv FROM inventory_report where id = in_id;
IF NOT FOUND THEN
   RETURN FALSE;
ELSIF inv.ap_trans_id IS NOT NULL OR inv.ar_trans_id IS NOT NULL THEN
   RAISE EXCEPTION &#39;Set is Already Approved!&#39;;
END IF;

DELETE FROM inventory_report_line where adjust_id = in_id;
DELETE FROM inventory_report where id = in_id;

RETURN TRUE;

END;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__get(in_id integer) -->
    <section id="public.function.inventory-adjust-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adjust-get-in-id-integer-title">
       inventory_adjust__get(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adjust-get-in-id-integer-titleabbrev">
       inventory_adjust__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_report</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM inventory_report WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__get_lines(in_id integer) -->
    <section id="public.function.inventory-adjust-get-lines-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-adjust-get-lines-in-id-integer-title">
       inventory_adjust__get_lines(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-adjust-get-lines-in-id-integer-titleabbrev">
       inventory_adjust__get_lines(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF inventory_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM inventory_report_line l WHERE adjust_id = $1
 ORDER BY parts_id;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__list(in_from_date date, in_to_date date, in_approved boolean) -->
    <section id="public.function.inventory-adjust-list-in-from-date-date-in-to-date-date-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.inventory-adjust-list-in-from-date-date-in-to-date-date-in-approved-boolean-title">
       inventory_adjust__list(in_from_date date, in_to_date date, in_approved boolean)
      </title>
      <titleabbrev id="public.function.inventory-adjust-list-in-from-date-date-in-to-date-date-in-approved-boolean-titleabbrev">
       inventory_adjust__list(in_from_date date, in_to_date date, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF inventory_report</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT * FROM inventory_report
 WHERE ($1 is null or transdate &gt;= $1)
       AND ($2 IS NULL OR transdate &lt;= $2)
       AND ($3 IS NULL OR $3 = (ar_trans_id IS NULL AND ap_trans_id IS NULL));

</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__save_info(in_transdate date, in_source text) -->
    <section id="public.function.inventory-adjust-save-info-in-transdate-date-in-source-text"
             xreflabel="()">
      <title id="public.function.inventory-adjust-save-info-in-transdate-date-in-source-text-title">
       inventory_adjust__save_info(in_transdate date, in_source text)
      </title>
      <titleabbrev id="public.function.inventory-adjust-save-info-in-transdate-date-in-source-text-titleabbrev">
       inventory_adjust__save_info(in_transdate date, in_source text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_report</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
INSERT INTO inventory_report(transdate, source)
VALUES ($1, $2)
RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function inventory_adjust__save_line(in_adjust_id integer, in_parts_id integer, in_counted numeric, in_expected numeric, in_variance numeric) -->
    <section id="public.function.inventory-adjust-save-line-in-adjust-id-integer-in-parts-id-integer-in-counted-numeric-in-expected-numeric-in-variance-numeric"
             xreflabel="()">
      <title id="public.function.inventory-adjust-save-line-in-adjust-id-integer-in-parts-id-integer-in-counted-numeric-in-expected-numeric-in-variance-numeric-title">
       inventory_adjust__save_line(in_adjust_id integer, in_parts_id integer, in_counted numeric, in_expected numeric, in_variance numeric)
      </title>
      <titleabbrev id="public.function.inventory-adjust-save-line-in-adjust-id-integer-in-parts-id-integer-in-counted-numeric-in-expected-numeric-in-variance-numeric-titleabbrev">
       inventory_adjust__save_line(in_adjust_id integer, in_parts_id integer, in_counted numeric, in_expected numeric, in_variance numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
INSERT INTO inventory_report_line
       (adjust_id, parts_id, counted, expected, variance)
VALUES ($1, $2, $3, $4, $5)
RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function inventory_create_report(in_transdate date) -->
    <section id="public.function.inventory-create-report-in-transdate-date"
             xreflabel="()">
      <title id="public.function.inventory-create-report-in-transdate-date-title">
       inventory_create_report(in_transdate date)
      </title>
      <titleabbrev id="public.function.inventory-create-report-in-transdate-date-titleabbrev">
       inventory_create_report(in_transdate date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_report</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        INSERT INTO inventory_report(transdate) values (in_transdate)
        RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function inventory_get_item_at_day(in_transdate date, in_partnumber text) -->
    <section id="public.function.inventory-get-item-at-day-in-transdate-date-in-partnumber-text"
             xreflabel="()">
      <title id="public.function.inventory-get-item-at-day-in-transdate-date-in-partnumber-text-title">
       inventory_get_item_at_day(in_transdate date, in_partnumber text)
      </title>
      <titleabbrev id="public.function.inventory-get-item-at-day-in-transdate-date-in-partnumber-text-titleabbrev">
       inventory_get_item_at_day(in_transdate date, in_partnumber text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE out_row RECORD;
        t_parts_id int;
        int_outrow RECORD;
BEGIN
        SELECT id INTO t_parts_id
        FROM parts
        WHERE (partnumber like in_partnumber|| &#39; %&#39;
                or partnumber = in_partnumber)
                and obsolete is not true
                and assembly is not true;

        SELECT * INTO out_row FROM parts WHERE id = t_parts_id;

        WITH RECURSIVE c AS (
             SELECT 1::numeric as multiplier, t_parts_id  as part_used,
                    t_parts_id as current_part_id
             UNION ALL
             SELECT c.multiplier * a.qty, t_parts_id as part_used,
                    a.parts_id as current_part_id
               FROM assembly a
               JOIN c ON c.current_part_id = a.id
        )
        SELECT  sum(coalesce(c.multiplier, 1) * i.qty) * -1
                AS onhand
        INTO int_outrow
        FROM parts p
        LEFT JOIN c ON c.part_used = t_parts_id
        JOIN invoice i ON (i.parts_id = p.id OR i.parts_id = c.current_part_id)
        JOIN (select id, transdate from ar
                UNION select id, transdate from ap) a ON (i.trans_id = a.id)

        WHERE (p.partnumber = in_partnumber
                or p.partnumber like in_partnumber || &#39; %&#39;)
                AND a.transdate &lt;= in_transdate
                AND assembly IS FALSE AND obsolete IS NOT TRUE
        GROUP BY p.id, p.partnumber, p.description, p.unit, p.listprice,
                p.sellprice, p.lastcost, p.priceupdate, p.weight,
                p.onhand, p.notes, p.makemodel, p.assembly, p.alternate,
                p.rop, p.inventory_accno_id, p.income_accno_id, p.expense_accno_id,
                p.bin, p.obsolete, p.bom, p.image, p.microfiche, p.partsgroup_id,
                p.avgcost;

        out_row.onhand := int_outrow.onhand;
        RETURN out_row;
END;
</programlisting>
      </para>
    </section>

<!-- Function inventory_report__add_line(in_report_id integer, in_parts_id integer, in_onhand integer, in_counted integer) -->
    <section id="public.function.inventory-report-add-line-in-report-id-integer-in-parts-id-integer-in-onhand-integer-in-counted-integer"
             xreflabel="()">
      <title id="public.function.inventory-report-add-line-in-report-id-integer-in-parts-id-integer-in-onhand-integer-in-counted-integer-title">
       inventory_report__add_line(in_report_id integer, in_parts_id integer, in_onhand integer, in_counted integer)
      </title>
      <titleabbrev id="public.function.inventory-report-add-line-in-report-id-integer-in-parts-id-integer-in-onhand-integer-in-counted-integer-titleabbrev">
       inventory_report__add_line(in_report_id integer, in_parts_id integer, in_onhand integer, in_counted integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>inventory_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        INSERT INTO inventory_report_line(adjust_id, parts_id, expected, counted)
        VALUES (in_report_id, in_parts_id, in_onhand, in_counted)
        RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function inventory_report__approve(in_id integer, in_ar_trans_id integer, in_ap_trans_id integer) -->
    <section id="public.function.inventory-report-approve-in-id-integer-in-ar-trans-id-integer-in-ap-trans-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-report-approve-in-id-integer-in-ar-trans-id-integer-in-ap-trans-id-integer-title">
       inventory_report__approve(in_id integer, in_ar_trans_id integer, in_ap_trans_id integer)
      </title>
      <titleabbrev id="public.function.inventory-report-approve-in-id-integer-in-ar-trans-id-integer-in-ap-trans-id-integer-titleabbrev">
       inventory_report__approve(in_id integer, in_ar_trans_id integer, in_ap_trans_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
update inventory_report
   SET ar_trans_id = $2, ap_trans_id = $3
 WHERE id = $1 AND ar_trans_id IS NULL AND ap_trans_id IS NULL
RETURNING id;
</programlisting>
      </para>
    </section>

<!-- Function inventory_report__delete(in_id integer) -->
    <section id="public.function.inventory-report-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.inventory-report-delete-in-id-integer-title">
       inventory_report__delete(in_id integer)
      </title>
      <titleabbrev id="public.function.inventory-report-delete-in-id-integer-titleabbrev">
       inventory_report__delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DELETE FROM inventory_report_line WHERE adjust_id = $1;
DELETE FROM inventory_report WHERE id = $1
RETURNING id;
</programlisting>
      </para>
    </section>

<!-- Function invoice__get_by_vendor_number(in_meta_number text, in_invoice_number text) -->
    <section id="public.function.invoice-get-by-vendor-number-in-meta-number-text-in-invoice-number-text"
             xreflabel="()">
      <title id="public.function.invoice-get-by-vendor-number-in-meta-number-text-in-invoice-number-text-title">
       invoice__get_by_vendor_number(in_meta_number text, in_invoice_number text)
      </title>
      <titleabbrev id="public.function.invoice-get-by-vendor-number-in-meta-number-text-in-invoice-number-text-titleabbrev">
       invoice__get_by_vendor_number(in_meta_number text, in_invoice_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>ap</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        SELECT * FROM ap WHERE entity_credit_account =
                (select id from entity_credit_account where entity_class = 1
                AND meta_number = in_meta_number)
                AND invnumber = in_invoice_number;
</programlisting>
      </para>
    </section>

<!-- Function is_leapyear(in_date date) -->
    <section id="public.function.is-leapyear-in-date-date"
             xreflabel="()">
      <title id="public.function.is-leapyear-in-date-date-title">
       is_leapyear(in_date date)
      </title>
      <titleabbrev id="public.function.is-leapyear-in-date-date-titleabbrev">
       is_leapyear(in_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if date is in a leapyear.  False if not.  Uses the built-in
PostgreSQL date handling, and no direct detection is done in our code.
        <programlisting>
    select extract(&#39;day&#39; FROM (
                           (extract(&#39;year&#39; FROM $1)::text
                           || &#39;-02-28&#39;)::date + &#39;1 day&#39;::interval)::date)
           = 29;
</programlisting>
      </para>
    </section>

<!-- Function is_same_month(in_date1 date, in_date2 date) -->
    <section id="public.function.is-same-month-in-date1-date-in-date2-date"
             xreflabel="()">
      <title id="public.function.is-same-month-in-date1-date-in-date2-date-title">
       is_same_month(in_date1 date, in_date2 date)
      </title>
      <titleabbrev id="public.function.is-same-month-in-date1-date-in-date2-date-titleabbrev">
       is_same_month(in_date1 date, in_date2 date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if the two dates are in the same month and year. False
otherwise.
        <programlisting>
SELECT is_same_year($1, $2)
       and extract (&#39;MONTH&#39; from $1) = extract (&#39;MONTH&#39; from $2);
</programlisting>
      </para>
    </section>

<!-- Function is_same_year(in_date1 date, in_date2 date) -->
    <section id="public.function.is-same-year-in-date1-date-in-date2-date"
             xreflabel="()">
      <title id="public.function.is-same-year-in-date1-date-in-date2-date-title">
       is_same_year(in_date1 date, in_date2 date)
      </title>
      <titleabbrev id="public.function.is-same-year-in-date1-date-in-date2-date-titleabbrev">
       is_same_year(in_date1 date, in_date2 date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if the two dates are in the same year, false otherwise.
        <programlisting>
SELECT  extract (&#39;YEAR&#39; from $1) = extract (&#39;YEAR&#39; from $2);
</programlisting>
      </para>
    </section>

<!-- Function journal__add(in_reference text, in_description text, in_journal integer, in_post_date date, in_approved boolean, in_is_template boolean, in_currency text) -->
    <section id="public.function.journal-add-in-reference-text-in-description-text-in-journal-integer-in-post-date-date-in-approved-boolean-in-is-template-boolean-in-currency-text"
             xreflabel="()">
      <title id="public.function.journal-add-in-reference-text-in-description-text-in-journal-integer-in-post-date-date-in-approved-boolean-in-is-template-boolean-in-currency-text-title">
       journal__add(in_reference text, in_description text, in_journal integer, in_post_date date, in_approved boolean, in_is_template boolean, in_currency text)
      </title>
      <titleabbrev id="public.function.journal-add-in-reference-text-in-description-text-in-journal-integer-in-post-date-date-in-approved-boolean-in-is-template-boolean-in-currency-text-titleabbrev">
       journal__add(in_reference text, in_description text, in_journal integer, in_post_date date, in_approved boolean, in_is_template boolean, in_currency text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>journal_entry</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        INSERT INTO journal_entry (reference, description, journal, post_date,
                        approved, is_template, effective_start, effective_end,
                        currency, entered_by)
        VALUES (coalesce($1, &#39;&#39;), $2, $3, $4,
                        coalesce($5 , false),
                        coalesce($6, false),
               $4, $4, $7, person__get_my_entity_id()) RETURNING *;
</programlisting>
      </para>
    </section>

<!-- Function journal__add_line(in_account_id integer, in_journal_id integer, in_amount numeric, in_cleared boolean, in_memo text, in_business_units integer[]) -->
    <section id="public.function.journal-add-line-in-account-id-integer-in-journal-id-integer-in-amount-numeric-in-cleared-boolean-in-memo-text-in-business-units-integerARRAY"
             xreflabel="()">
      <title id="public.function.journal-add-line-in-account-id-integer-in-journal-id-integer-in-amount-numeric-in-cleared-boolean-in-memo-text-in-business-units-integerARRAY-title">
       journal__add_line(in_account_id integer, in_journal_id integer, in_amount numeric, in_cleared boolean, in_memo text, in_business_units integer[])
      </title>
      <titleabbrev id="public.function.journal-add-line-in-account-id-integer-in-journal-id-integer-in-amount-numeric-in-cleared-boolean-in-memo-text-in-business-units-integerARRAY-titleabbrev">
       journal__add_line(in_account_id integer, in_journal_id integer, in_amount numeric, in_cleared boolean, in_memo text, in_business_units integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>journal_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        INSERT INTO journal_line(account_id, journal_id, amount, cleared)
        VALUES (in_account_id, in_journal_id, in_amount,
                coalesce(in_cleared, false));

        INSERT INTO business_unit_jl(entry_id, bu_class, bu_id)
        SELECT currval(&#39;journal_line_id_seq&#39;), class_id, id
          FROM business_unit
         WHERE id = any(in_business_units);

        SELECT * FROM journal_line where id = currval(&#39;journal_line_id_seq&#39;);
</programlisting>
      </para>
    </section>

<!-- Function journal__delete(in_journal_id integer) -->
    <section id="public.function.journal-delete-in-journal-id-integer"
             xreflabel="()">
      <title id="public.function.journal-delete-in-journal-id-integer-title">
       journal__delete(in_journal_id integer)
      </title>
      <titleabbrev id="public.function.journal-delete-in-journal-id-integer-titleabbrev">
       journal__delete(in_journal_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
  DELETE FROM journal_line WHERE journal_id = in_journal_id;

  DELETE FROM journal_entry WHERE id = in_journal_id;
</programlisting>
      </para>
    </section>

<!-- Function journal__get_entry(in_id integer) -->
    <section id="public.function.journal-get-entry-in-id-integer"
             xreflabel="()">
      <title id="public.function.journal-get-entry-in-id-integer-title">
       journal__get_entry(in_id integer)
      </title>
      <titleabbrev id="public.function.journal-get-entry-in-id-integer-titleabbrev">
       journal__get_entry(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>journal_entry</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM journal_entry where id = $1;
</programlisting>
      </para>
    </section>

<!-- Function journal__get_invoice(in_id integer) -->
    <section id="public.function.journal-get-invoice-in-id-integer"
             xreflabel="()">
      <title id="public.function.journal-get-invoice-in-id-integer-title">
       journal__get_invoice(in_id integer)
      </title>
      <titleabbrev id="public.function.journal-get-invoice-in-id-integer-titleabbrev">
       journal__get_invoice(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>eca_invoice</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM eca_invoice where journal_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function journal__lines(in_id integer) -->
    <section id="public.function.journal-lines-in-id-integer"
             xreflabel="()">
      <title id="public.function.journal-lines-in-id-integer-title">
       journal__lines(in_id integer)
      </title>
      <titleabbrev id="public.function.journal-lines-in-id-integer-titleabbrev">
       journal__lines(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF journal_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
select * from journal_line where journal_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function journal__make_invoice(in_order_id integer, in_journal_id integer, in_on_hold boolean, in_reverse boolean, in_credit_id integer, in_language_code character varying) -->
    <section id="public.function.journal-make-invoice-in-order-id-integer-in-journal-id-integer-in-on-hold-boolean-in-reverse-boolean-in-credit-id-integer-in-language-code-character-varying"
             xreflabel="()">
      <title id="public.function.journal-make-invoice-in-order-id-integer-in-journal-id-integer-in-on-hold-boolean-in-reverse-boolean-in-credit-id-integer-in-language-code-character-varying-title">
       journal__make_invoice(in_order_id integer, in_journal_id integer, in_on_hold boolean, in_reverse boolean, in_credit_id integer, in_language_code character varying)
      </title>
      <titleabbrev id="public.function.journal-make-invoice-in-order-id-integer-in-journal-id-integer-in-on-hold-boolean-in-reverse-boolean-in-credit-id-integer-in-language-code-character-varying-titleabbrev">
       journal__make_invoice(in_order_id integer, in_journal_id integer, in_on_hold boolean, in_reverse boolean, in_credit_id integer, in_language_code character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>eca_invoice</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval eca_invoice;
BEGIN
        INSERT INTO eca_invoice (order_id, journal_id, on_hold, reverse,
                credit_id, language_code, due)
        VALUES (in_order_id, in_journal_id, coalesce(in_on_hold, false),
                in_reverse, in_credit_id, in_language_code, &#39;today&#39;);

        SELECT * INTO retval FROM eca_invoice WHERE journal_id = in_journal_id;

        RETURN retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function journal__save_recurring_print(in_id integer, in_formname text, in_printer text) -->
    <section id="public.function.journal-save-recurring-print-in-id-integer-in-formname-text-in-printer-text"
             xreflabel="()">
      <title id="public.function.journal-save-recurring-print-in-id-integer-in-formname-text-in-printer-text-title">
       journal__save_recurring_print(in_id integer, in_formname text, in_printer text)
      </title>
      <titleabbrev id="public.function.journal-save-recurring-print-in-id-integer-in-formname-text-in-printer-text-titleabbrev">
       journal__save_recurring_print(in_id integer, in_formname text, in_printer text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>recurringprint</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
insert into recurringprint (id, formname, format, printer)
values ($1, $2, &#39;PDF&#39;, $3)
returning *;
</programlisting>
      </para>
    </section>

<!-- Function journal__search(in_reference text, in_description text, in_entry_type integer, in_transaction_date date, in_approved boolean, in_department_id integer, in_is_template boolean, in_meta_number text, in_entity_class integer, in_recurring boolean) -->
    <section id="public.function.journal-search-in-reference-text-in-description-text-in-entry-type-integer-in-transaction-date-date-in-approved-boolean-in-department-id-integer-in-is-template-boolean-in-meta-number-text-in-entity-class-integer-in-recurring-boolean"
             xreflabel="()">
      <title id="public.function.journal-search-in-reference-text-in-description-text-in-entry-type-integer-in-transaction-date-date-in-approved-boolean-in-department-id-integer-in-is-template-boolean-in-meta-number-text-in-entity-class-integer-in-recurring-boolean-title">
       journal__search(in_reference text, in_description text, in_entry_type integer, in_transaction_date date, in_approved boolean, in_department_id integer, in_is_template boolean, in_meta_number text, in_entity_class integer, in_recurring boolean)
      </title>
      <titleabbrev id="public.function.journal-search-in-reference-text-in-description-text-in-entry-type-integer-in-transaction-date-date-in-approved-boolean-in-department-id-integer-in-is-template-boolean-in-meta-number-text-in-entity-class-integer-in-recurring-boolean-titleabbrev">
       journal__search(in_reference text, in_description text, in_entry_type integer, in_transaction_date date, in_approved boolean, in_department_id integer, in_is_template boolean, in_meta_number text, in_entity_class integer, in_recurring boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF journal_search_result</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval journal_search_result;
BEGIN
        FOR retval IN
                SELECT j.id, j.reference , j.description, j.journal,
                        j.post_date , j.approved,
                        j.is_template, eca.meta_number,
                        e.name, ec.class,
                        coalesce(
                          r.startdate + 0, -- r.recurring_interval,
                          j.post_date )
                FROM journal_entry j
                LEFT JOIN eca_invoice i ON (i.journal_id = j.id)
                LEFT JOIN entity_credit_account eca ON (eca.id = credit_id)
                LEFT JOIN entity e ON (eca.entity_id = e.id)
                LEFT JOIN entity_class ec ON (eca.entity_class = ec.id)
                LEFT JOIN recurring r ON j.id = r.id
--              WHERE (in_reference IS NULL OR in_reference = j.reference) AND
--                      (in_description IS NULL
--                              or in_description = j.description) AND
--                      (in_entry_type is null or in_entry_type = j.journal)
--                      and (in_transaction_date is null
--                              or in_transaction_date = j.post_date) and
--                      j.approved = coalesce(in_approved, true) and
--                      j.is_template = coalesce(in_is_template, false) and
--                      (in_meta_number is null
--                              or eca.meta_number = in_meta_number) and
--                      (in_entity_class is null
--                              or eca.entity_class = in_entity_class) AND
 --                       (in_recurring IS NOT TRUE OR
  --                              coalesce(r.startdate, r.nextdate) &lt;= now()::date
   --                     )
        LOOP
                RETURN NEXT retval;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function journal__validate_entry(in_id integer) -->
    <section id="public.function.journal-validate-entry-in-id-integer"
             xreflabel="()">
      <title id="public.function.journal-validate-entry-in-id-integer-title">
       journal__validate_entry(in_id integer)
      </title>
      <titleabbrev id="public.function.journal-validate-entry-in-id-integer-titleabbrev">
       journal__validate_entry(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        SELECT sum(amount) = 0 FROM journal_line WHERE journal_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function lastcost(integer) -->
    <section id="public.function.lastcost-integer"
             xreflabel="()">
      <title id="public.function.lastcost-integer-title">
       lastcost(integer)
      </title>
      <titleabbrev id="public.function.lastcost-integer-titleabbrev">
       lastcost(integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>double precision</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

DECLARE

v_cost float;
v_parts_id alias for $1;

BEGIN

  SELECT INTO v_cost sellprice FROM invoice i
  JOIN ap a ON (a.id = i.trans_id)
  WHERE i.parts_id = v_parts_id
  ORDER BY a.transdate desc, a.id desc
  LIMIT 1;

  IF v_cost IS NULL THEN
    v_cost := 0;
  END IF;

RETURN v_cost;
END;
</programlisting>
      </para>
    </section>

<!-- Function leap_days(in_year_from integer, in_year_to integer) -->
    <section id="public.function.leap-days-in-year-from-integer-in-year-to-integer"
             xreflabel="()">
      <title id="public.function.leap-days-in-year-from-integer-in-year-to-integer-title">
       leap_days(in_year_from integer, in_year_to integer)
      </title>
      <titleabbrev id="public.function.leap-days-in-year-from-integer-in-year-to-integer-titleabbrev">
       leap_days(in_year_from integer, in_year_to integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns the number of leap years between the two year inputs, inclusive.
        <programlisting>
   SELECT count(*)::int
   FROM generate_series($1, $2)
   WHERE is_leapyear((generate_series::text || &#39;-01-01&#39;)::date);
</programlisting>
      </para>
    </section>

<!-- Function list_taxforms(in_entity_id integer) -->
    <section id="public.function.list-taxforms-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.list-taxforms-in-entity-id-integer-title">
       list_taxforms(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.list-taxforms-in-entity-id-integer-titleabbrev">
       list_taxforms(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF country_tax_form</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a list of tax forms for the entity&apos;s country.
        <programlisting>
DECLARE t_country_tax_form country_tax_form;
BEGIN

        FOR t_country_tax_form IN

                      SELECT *
                            FROM country_tax_form where country_id in(SELECT country_id from entity where id=in_entity_id)
        LOOP

        RETURN NEXT t_country_tax_form;

        END LOOP;

END;
</programlisting>
      </para>
    </section>

<!-- Function location__deactivate(in_id integer) -->
    <section id="public.function.location-deactivate-in-id-integer"
             xreflabel="()">
      <title id="public.function.location-deactivate-in-id-integer-title">
       location__deactivate(in_id integer)
      </title>
      <titleabbrev id="public.function.location-deactivate-in-id-integer-titleabbrev">
       location__deactivate(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>location</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

UPDATE location set active = false, inactive_date = now()
 WHERE id = $1;

SELECT * FROM location WHERE id = 1;

</programlisting>
      </para>
    </section>

<!-- Function location__get(in_id integer) -->
    <section id="public.function.location-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.location-get-in-id-integer-title">
       location__get(in_id integer)
      </title>
      <titleabbrev id="public.function.location-get-in-id-integer-titleabbrev">
       location__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>location</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the location specified by in_id.
        <programlisting>
        SELECT * FROM location WHERE id = in_id;
</programlisting>
      </para>
    </section>

<!-- Function location_delete(in_id integer) -->
    <section id="public.function.location-delete-in-id-integer"
             xreflabel="()">
      <title id="public.function.location-delete-in-id-integer-title">
       location_delete(in_id integer)
      </title>
      <titleabbrev id="public.function.location-delete-in-id-integer-titleabbrev">
       location_delete(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>void</seg>
        </seglistitem>
       </segmentedlist>
 
        DELETES the location specified by in_id.  Does not return a value.
        <programlisting>
        DELETE FROM location WHERE id = in_id;
</programlisting>
      </para>
    </section>

<!-- Function location_list_class() -->
    <section id="public.function.location-list-class"
             xreflabel="()">
      <title id="public.function.location-list-class-title">
       location_list_class()
      </title>
      <titleabbrev id="public.function.location-list-class-titleabbrev">
       location_list_class()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF location_class_item</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists location classes, by default in order entered.
        <programlisting>
                SELECT l.*, as_array(e.entity_class)
                  FROM location_class l
                  JOIN location_class_to_entity_class e
                       ON (l.id = e.location_class)
              GROUP BY l.id, l.class, l.authoritative
              ORDER BY l.id;
</programlisting>
      </para>
    </section>

<!-- Function location_list_country() -->
    <section id="public.function.location-list-country"
             xreflabel="()">
      <title id="public.function.location-list-country-title">
       location_list_country()
      </title>
      <titleabbrev id="public.function.location-list-country-titleabbrev">
       location_list_country()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF country</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists countries, by default in alphabetical order.
        <programlisting>
                SELECT * FROM country ORDER BY name;
</programlisting>
      </para>
    </section>

<!-- Function location_save(in_location_id integer, in_address1 text, in_address2 text, in_address3 text, in_city text, in_state text, in_zipcode text, in_country integer) -->
    <section id="public.function.location-save-in-location-id-integer-in-address1-text-in-address2-text-in-address3-text-in-city-text-in-state-text-in-zipcode-text-in-country-integer"
             xreflabel="()">
      <title id="public.function.location-save-in-location-id-integer-in-address1-text-in-address2-text-in-address3-text-in-city-text-in-state-text-in-zipcode-text-in-country-integer-title">
       location_save(in_location_id integer, in_address1 text, in_address2 text, in_address3 text, in_city text, in_state text, in_zipcode text, in_country integer)
      </title>
      <titleabbrev id="public.function.location-save-in-location-id-integer-in-address1-text-in-address2-text-in-address3-text-in-city-text-in-state-text-in-zipcode-text-in-country-integer-titleabbrev">
       location_save(in_location_id integer, in_address1 text, in_address2 text, in_address3 text, in_city text, in_state text, in_zipcode text, in_country integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Note that this does NOT override the data in the database unless in_location_id is specified.
Instead we search for locations matching the desired specifications and if none
are found, we insert one.  Either way, the return value of the location can be
used for mapping to other things.  This is necessary because locations are
only loosly coupled with entities, etc.
        <programlisting>
DECLARE
        location_id integer;
        location_row RECORD;
BEGIN

        IF in_location_id IS NULL THEN
            SELECT id INTO location_id FROM location
            WHERE line_one = in_address1 AND line_two = in_address2
                  AND line_three = in_address3 AND in_city = city
                  AND in_state = state AND in_zipcode = mail_code
                  AND in_country = country_id
            LIMIT 1;

            IF NOT FOUND THEN
            -- Straight insert.
            location_id = nextval(&#39;location_id_seq&#39;);
            INSERT INTO location (
                id,
                line_one,
                line_two,
                line_three,
                city,
                state,
                mail_code,
                country_id)
            VALUES (
                location_id,
                in_address1,
                in_address2,
                in_address3,
                in_city,
                in_state,
                in_zipcode,
                in_country
                );
            END IF;
            return location_id;
        ELSE
            RAISE NOTICE &#39;Overwriting location id %&#39;, in_location_id;
            -- Test it.
            SELECT * INTO location_row FROM location WHERE id = in_location_id;
            IF NOT FOUND THEN
                -- Tricky users are lying to us.
                RAISE EXCEPTION &#39;location_save called with nonexistant location ID %&#39;, in_location_id;
            ELSE
                -- Okay, we&#39;re good.

                UPDATE location SET
                    line_one = in_address1,
                    line_two = in_address2,
                    line_three = in_address3,
                    city = in_city,
                    state = in_state,
                    mail_code = in_zipcode,
                    country_id = in_country
                WHERE id = in_location_id;
                return in_location_id;
            END IF;
        END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function lock_record(in_id integer, in_session_id integer) -->
    <section id="public.function.lock-record-in-id-integer-in-session-id-integer"
             xreflabel="()">
      <title id="public.function.lock-record-in-id-integer-in-session-id-integer-title">
       lock_record(in_id integer, in_session_id integer)
      </title>
      <titleabbrev id="public.function.lock-record-in-id-integer-in-session-id-integer-titleabbrev">
       lock_record(in_id integer, in_session_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function seeks to lock a record with an id of in_id to a session with an
id of in_session_id.  If possible, it returns true.  If it is already locked,
false.  These are not hard locks and the application is free to disregard or
not even ask.  They time out when the session is destroyed.

        <programlisting>
declare
   locked int;
begin
   SELECT locked_by into locked from transactions where id = $1;
   IF NOT FOUND THEN
        RETURN FALSE;
   ELSEIF locked is not null AND locked &lt;&gt; $2 THEN
        RETURN FALSE;
   END IF;
   UPDATE transactions set locked_by = $2 where id = $1;
   RETURN TRUE;
end;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__create_role(in_role text) -->
    <section id="public.function.lsmb-create-role-in-role-text"
             xreflabel="()">
      <title id="public.function.lsmb-create-role-in-role-text-title">
       lsmb__create_role(in_role text)
      </title>
      <titleabbrev id="public.function.lsmb-create-role-in-role-text-titleabbrev">
       lsmb__create_role(in_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
  PERFORM * FROM pg_roles WHERE rolname = lsmb__role(in_role);
  IF FOUND THEN
     RETURN TRUE;
  END IF;

  EXECUTE &#39;CREATE ROLE &#39; || quote_ident(lsmb__role(in_role))
  || &#39; WITH INHERIT NOLOGIN&#39;;

  RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__decompose_timestamp(in_timestamp timestamp with time zone) -->
    <section id="public.function.lsmb-decompose-timestamp-in-timestamp-timestamp-with-time-zone"
             xreflabel="()">
      <title id="public.function.lsmb-decompose-timestamp-in-timestamp-timestamp-with-time-zone-title">
       lsmb__decompose_timestamp(in_timestamp timestamp with time zone)
      </title>
      <titleabbrev id="public.function.lsmb-decompose-timestamp-in-timestamp-timestamp-with-time-zone-titleabbrev">
       lsmb__decompose_timestamp(in_timestamp timestamp with time zone)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>lsmb_date_fields</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT extract(&#39;century&#39; from $1) as century,
       extract(&#39;decade&#39; from $1) as decade,
       extract(&#39;year&#39; from $1) as year,
       extract(&#39;month&#39; from $1) as month,
       extract(&#39;day&#39; from $1) as day,
       extract(&#39;hour&#39; from $1) as hour,
       extract(&#39;minute&#39; from $1) as minute,
       extract(&#39;second&#39; from $1) as second,
       extract(&#39;quarter&#39; from $1) as quarter,
       extract(&#39;doy&#39; from $1) as doy,
       extract(&#39;dow&#39; from $1) as dow,
       extract(&#39;week&#39; from $1) as week,
       extract(&#39;epoch&#39; from $1) as epoch,
       $1::date as as_date,
       $1::time as as_time;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__grant_exec(in_role text, in_func text) -->
    <section id="public.function.lsmb-grant-exec-in-role-text-in-func-text"
             xreflabel="()">
      <title id="public.function.lsmb-grant-exec-in-role-text-in-func-text-title">
       lsmb__grant_exec(in_role text, in_func text)
      </title>
      <titleabbrev id="public.function.lsmb-grant-exec-in-role-text-in-func-text-titleabbrev">
       lsmb__grant_exec(in_role text, in_func text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
   EXECUTE &#39;GRANT EXECUTE ON FUNCTION &#39; || in_func || &#39; TO &#39;
   || quote_ident(lsmb__role(in_role));
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__grant_menu(in_role text, in_node_id integer, in_perm_type text) -->
    <section id="public.function.lsmb-grant-menu-in-role-text-in-node-id-integer-in-perm-type-text"
             xreflabel="()">
      <title id="public.function.lsmb-grant-menu-in-role-text-in-node-id-integer-in-perm-type-text-title">
       lsmb__grant_menu(in_role text, in_node_id integer, in_perm_type text)
      </title>
      <titleabbrev id="public.function.lsmb-grant-menu-in-role-text-in-node-id-integer-in-perm-type-text-titleabbrev">
       lsmb__grant_menu(in_role text, in_node_id integer, in_perm_type text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
   PERFORM * FROM pg_roles WHERE rolname = lsmb__role(in_role);
   IF NOT FOUND THEN
      RAISE EXCEPTION &#39;Role not found&#39;;
   END IF;
   PERFORM * FROM menu_attribute
     WHERE attribute = &#39;menu&#39; AND node_id = in_node_id;
   IF FOUND THEN
      RAISE EXCEPTION &#39;Cannot grant to submenu&#39;;
   END IF;
   IF in_perm_type NOT IN (&#39;allow&#39;, &#39;deny&#39;) THEN
      RAISE EXCEPTION &#39;Invalid perm type&#39;;
   END IF;
   PERFORM * FROM menu_acl
     WHERE node_id = in_node_id AND role_name = lsmb__role(in_role)
           AND acl_type = in_perm_type;
   IF FOUND THEN RETURN TRUE;
   END IF;
   INSERT INTO menu_acl (node_id, role_name, acl_type)
   VALUES (in_node_id, lsmb__role(in_role), in_perm_type);
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__grant_perms(in_role text, in_table text, in_perms text) -->
    <section id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text"
             xreflabel="()">
      <title id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text-title">
       lsmb__grant_perms(in_role text, in_table text, in_perms text)
      </title>
      <titleabbrev id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text-titleabbrev">
       lsmb__grant_perms(in_role text, in_table text, in_perms text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
   IF upper(in_perms) NOT IN (&#39;ALL&#39;, &#39;INSERT&#39;, &#39;UPDATE&#39;, &#39;SELECT&#39;, &#39;DELETE&#39;) THEN
      RAISE EXCEPTION &#39;Invalid permission&#39;;
   END IF;
   EXECUTE &#39;GRANT &#39; || in_perms || &#39; ON &#39; || quote_ident(in_table)
   || &#39; TO &#39; ||  quote_ident(lsmb__role(in_role));

   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__grant_perms(in_role text, in_table text, in_perms text, in_cols text[]) -->
    <section id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text-in-cols-textARRAY"
             xreflabel="()">
      <title id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text-in-cols-textARRAY-title">
       lsmb__grant_perms(in_role text, in_table text, in_perms text, in_cols text[])
      </title>
      <titleabbrev id="public.function.lsmb-grant-perms-in-role-text-in-table-text-in-perms-text-in-cols-textARRAY-titleabbrev">
       lsmb__grant_perms(in_role text, in_table text, in_perms text, in_cols text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
   IF upper(in_perms) NOT IN (&#39;ALL&#39;, &#39;INSERT&#39;, &#39;UPDATE&#39;, &#39;SELECT&#39;, &#39;DELETE&#39;) THEN
      RAISE EXCEPTION &#39;Invalid permission&#39;;
   END IF;
   EXECUTE &#39;GRANT &#39; || in_perms
   || &#39;(&#39; || array_to_string(quote_ident_array(in_cols), &#39;, &#39;)
   || &#39;) ON &#39; || quote_ident(in_table)|| &#39; TO &#39;
   ||  quote_ident(lsmb__role(in_role));
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__grant_role(in_child text, in_parent text) -->
    <section id="public.function.lsmb-grant-role-in-child-text-in-parent-text"
             xreflabel="()">
      <title id="public.function.lsmb-grant-role-in-child-text-in-parent-text-title">
       lsmb__grant_role(in_child text, in_parent text)
      </title>
      <titleabbrev id="public.function.lsmb-grant-role-in-child-text-in-parent-text-titleabbrev">
       lsmb__grant_role(in_child text, in_parent text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
   EXECUTE &#39;GRANT &#39; || quote_ident(lsmb__role(in_parent)) || &#39; TO &#39;
   || quote_ident(lsmb__role(in_child));
   RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__is_allowed_role(in_rolelist text[]) -->
    <section id="public.function.lsmb-is-allowed-role-in-rolelist-textARRAY"
             xreflabel="()">
      <title id="public.function.lsmb-is-allowed-role-in-rolelist-textARRAY-title">
       lsmb__is_allowed_role(in_rolelist text[])
      </title>
      <titleabbrev id="public.function.lsmb-is-allowed-role-in-rolelist-textARRAY-titleabbrev">
       lsmb__is_allowed_role(in_rolelist text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
select bool_and(pg_has_role(lsmb__role(r), &#39;USAGE&#39;))
  from unnest(in_rolelist) r;
</programlisting>
      </para>
    </section>

<!-- Function lsmb__max_date() -->
    <section id="public.function.lsmb-max-date"
             xreflabel="()">
      <title id="public.function.lsmb-max-date-title">
       lsmb__max_date()
      </title>
      <titleabbrev id="public.function.lsmb-max-date-titleabbrev">
       lsmb__max_date()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>date</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT max(transdate) FROM acc_trans; </programlisting>
      </para>
    </section>

<!-- Function lsmb__min_date() -->
    <section id="public.function.lsmb-min-date"
             xreflabel="()">
      <title id="public.function.lsmb-min-date-title">
       lsmb__min_date()
      </title>
      <titleabbrev id="public.function.lsmb-min-date-titleabbrev">
       lsmb__min_date()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>date</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT min(transdate) from acc_trans; </programlisting>
      </para>
    </section>

<!-- Function lsmb__role(global_role text) -->
    <section id="public.function.lsmb-role-global-role-text"
             xreflabel="()">
      <title id="public.function.lsmb-role-global-role-text-title">
       lsmb__role(global_role text)
      </title>
      <titleabbrev id="public.function.lsmb-role-global-role-text-titleabbrev">
       lsmb__role(global_role text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text</seg>
        </seglistitem>
       </segmentedlist>
 
        Prepends the role prefix to a role name.

E.g. &apos;contact_edit&apos; is converted to &apos;lsmb_mycompany__contact_edit&apos;

        <programlisting> select lsmb__role_prefix() || $1; </programlisting>
      </para>
    </section>

<!-- Function lsmb__role_prefix() -->
    <section id="public.function.lsmb-role-prefix"
             xreflabel="()">
      <title id="public.function.lsmb-role-prefix-title">
       lsmb__role_prefix()
      </title>
      <titleabbrev id="public.function.lsmb-role-prefix-titleabbrev">
       lsmb__role_prefix()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the prefix text to be used for roles. E.g.  &apos;lsmb__mycompany_&apos; 
        <programlisting> select coalesce((setting_get(&#39;role_prefix&#39;)).value,
                   &#39;lsmb_&#39; || current_database() || &#39;__&#39;); </programlisting>
      </para>
    </section>

<!-- Function lsmb_module__get(in_id integer) -->
    <section id="public.function.lsmb-module-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.lsmb-module-get-in-id-integer-title">
       lsmb_module__get(in_id integer)
      </title>
      <titleabbrev id="public.function.lsmb-module-get-in-id-integer-titleabbrev">
       lsmb_module__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>lsmb_module</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves a single module&apos;s info by id. 
        <programlisting> SELECT * FROM lsmb_module where id = $1; </programlisting>
      </para>
    </section>

<!-- Function lsmb_module__list() -->
    <section id="public.function.lsmb-module-list"
             xreflabel="()">
      <title id="public.function.lsmb-module-list-title">
       lsmb_module__list()
      </title>
      <titleabbrev id="public.function.lsmb-module-list-titleabbrev">
       lsmb_module__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF lsmb_module</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of all defined modules, ordered by id. 
        <programlisting> SELECT * FROM lsmb_module ORDER BY id </programlisting>
      </para>
    </section>

<!-- Function menu_children(in_parent_id integer) -->
    <section id="public.function.menu-children-in-parent-id-integer"
             xreflabel="()">
      <title id="public.function.menu-children-in-parent-id-integer-title">
       menu_children(in_parent_id integer)
      </title>
      <titleabbrev id="public.function.menu-children-in-parent-id-integer-titleabbrev">
       menu_children(in_parent_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF menu_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns all menu  items which are children of in_parent_id
(the only input parameter).

It is thus similar to menu_generate() but it only returns the menu items
associated with nodes directly descendant from the parent.  It is used for
menues for frameless browsers.
        <programlisting>
SELECT * FROM menu_generate() where parent = $1;
</programlisting>
      </para>
    </section>

<!-- Function menu_generate() -->
    <section id="public.function.menu-generate"
             xreflabel="()">
      <title id="public.function.menu-generate-title">
       menu_generate()
      </title>
      <titleabbrev id="public.function.menu-generate-titleabbrev">
       menu_generate()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF menu_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function returns the complete menu tree.  It is used to generate nested
menus for the web interface.

        <programlisting>
               WITH RECURSIVE tree (path, id, parent, level, positions)
                               AS (select id::text as path, id, parent,
                                           0 as level, position::text
                                      FROM menu_node where parent is null
                                     UNION
                                    select path || &#39;,&#39; || n.id::text, n.id,
                                           n.parent,
                                           t.level + 1,
                                           t.positions || &#39;,&#39; || n.position
                                      FROM menu_node n
                                      JOIN tree t ON t.id = n.parent)
                SELECT n.position, n.id, c.level, n.label, c.path, n.parent,
                       to_args(array[ma.attribute, ma.value])
                FROM tree c
                JOIN menu_node n USING(id)
                JOIN menu_attribute ma ON (n.id = ma.node_id)
               WHERE n.id IN (select node_id
                                FROM menu_acl acl
                          LEFT JOIN pg_roles pr on pr.rolname = acl.role_name
                               WHERE CASE WHEN role_name
                                                           ilike &#39;public&#39;
                                                      THEN true
                                                      WHEN rolname IS NULL
                                                      THEN FALSE
                                                      ELSE pg_has_role(rolname,
                                                                       &#39;USAGE&#39;)
                                      END
                            GROUP BY node_id
                              HAVING bool_and(CASE WHEN acl_type ilike &#39;DENY&#39;
                                                   THEN FALSE
                                                   WHEN acl_type ilike &#39;ALLOW&#39;
                                                   THEN TRUE
                                                END))
                    or exists (select cn.id, cc.path
                                 FROM tree cc
                                 JOIN menu_node cn USING(id)
                                WHERE cn.id IN
                                      (select node_id
                                         FROM menu_acl acl
                                    LEFT JOIN pg_roles pr
                                              on pr.rolname = acl.role_name
                                        WHERE CASE WHEN rolname
                                                           ilike &#39;public&#39;
                                                      THEN true
                                                      WHEN rolname IS NULL
                                                      THEN FALSE
                                                      ELSE pg_has_role(rolname,
                                                                       &#39;USAGE&#39;)
                                                END
                                     GROUP BY node_id
                                       HAVING bool_and(CASE WHEN acl_type
                                                                 ilike &#39;DENY&#39;
                                                            THEN false
                                                            WHEN acl_type
                                                                 ilike &#39;ALLOW&#39;
                                                            THEN TRUE
                                                         END))
                                       and cc.path::text
                                           like c.path::text || &#39;,%&#39;)
            GROUP BY n.position, n.id, c.level, n.label, c.path, c.positions,
                     n.parent
            ORDER BY string_to_array(c.positions, &#39;,&#39;)::int[]
</programlisting>
      </para>
    </section>

<!-- Function menu_insert(in_parent_id integer, in_position integer, in_label text) -->
    <section id="public.function.menu-insert-in-parent-id-integer-in-position-integer-in-label-text"
             xreflabel="()">
      <title id="public.function.menu-insert-in-parent-id-integer-in-position-integer-in-label-text-title">
       menu_insert(in_parent_id integer, in_position integer, in_label text)
      </title>
      <titleabbrev id="public.function.menu-insert-in-parent-id-integer-in-position-integer-in-label-text-titleabbrev">
       menu_insert(in_parent_id integer, in_position integer, in_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function inserts menu items at arbitrary positions.  The arguments are, in
order:  parent, position, label.  The return value is the id number of the menu
item created. 
        <programlisting>
DECLARE
        new_id int;
BEGIN
        UPDATE menu_node
        SET position = position * -1
        WHERE parent = in_parent_id
                AND position &gt;= in_position;

        INSERT INTO menu_node (parent, position, label)
        VALUES (in_parent_id, in_position, in_label);

        SELECT INTO new_id currval(&#39;menu_node_id_seq&#39;);

        UPDATE menu_node
        SET position = (position * -1) + 1
        WHERE parent = in_parent_id
                AND position &lt; 0;

        RETURN new_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function mfg_lot__commit(in_id integer) -->
    <section id="public.function.mfg-lot-commit-in-id-integer"
             xreflabel="()">
      <title id="public.function.mfg-lot-commit-in-id-integer-title">
       mfg_lot__commit(in_id integer)
      </title>
      <titleabbrev id="public.function.mfg-lot-commit-in-id-integer-titleabbrev">
       mfg_lot__commit(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE t_mfg_lot mfg_lot;
BEGIN
    SELECT * INTO t_mfg_lot FROM mfg_lot WHERE id = $1;
    IF NOT FOUND THEN
        RAISE EXCEPTION &#39;Lot not found&#39;;
    END IF;

    UPDATE parts SET onhand = onhand
                              - (select t_mfg_lot.qty from mfg_lot_item
                                  WHERE parts_id = parts.id AND
                                        mfg_lot_id = $1)
     WHERE id in (select parts_id from mfg_lot_item
                   WHERE mfg_lot_id = $1);

    UPDATE parts SET onhand = onhand + t_mfg_lot.qty
     where id = t_mfg_lot.parts_id;

    INSERT INTO gl (reference, description, transdate, approved)
    values (&#39;mfg-&#39; || $1::TEXT, &#39;Manufacturing lot&#39;,
            now(), true);

    INSERT INTO invoice (trans_id, parts_id, qty, allocated)
    SELECT currval(&#39;id&#39;)::int, parts_id, qty, 0
      FROM mfg_lot_item WHERE mfg_lot_id = $1;

    PERFORM cogs__add_for_ar_line(id) FROM invoice
      WHERE trans_id = currval(&#39;id&#39;)::int;


    PERFORM * FROM invoice
      WHERE qty + allocated &lt;&gt; 0 AND trans_id = currval(&#39;id&#39;)::int;

    IF FOUND THEN
       RAISE EXCEPTION &#39;Not enough parts in stock&#39;;
    END IF;

    INSERT INTO invoice (trans_id, parts_id, qty, allocated, sellprice)
    SELECT currval(&#39;id&#39;)::int, t_mfg_lot.parts_id, t_mfg_lot.qty * -1, 0,
           sum(amount) / t_mfg_lot.qty
      FROM acc_trans
     WHERE amount &lt; 0 and trans_id = currval(&#39;id&#39;)::int;

    PERFORM cogs__add_for_ap_line(currval(&#39;invoice_id_seq&#39;)::int);

    -- move from reverse COGS.
    INSERT INTO acc_trans(trans_id, chart_id, transdate, amount)
    SELECT trans_id, chart_id, transdate, amount * -1
      FROM acc_trans
     WHERE amount &lt; 0 and trans_id = currval(&#39;id&#39;)::int;

    -- difference goes into inventory
    INSERT INTO acc_trans(trans_id, transdate, amount, chart_id)
    SELECT trans_id, now(), sum(amount) * -1,
           (select inventory_accno_id from parts where id = t_mfg_lot.parts_id)
      FROM acc_trans
     WHERE trans_id = currval(&#39;id&#39;)::int
  GROUP BY trans_id;


    RETURN t_mfg_lot.qty;
END;
</programlisting>
      </para>
    </section>

<!-- Function months_passed(in_start timestamp without time zone, in_end timestamp without time zone) -->
    <section id="public.function.months-passed-in-start-timestamp-without-time-zone-in-end-timestamp-without-time-zone"
             xreflabel="()">
      <title id="public.function.months-passed-in-start-timestamp-without-time-zone-in-end-timestamp-without-time-zone-title">
       months_passed(in_start timestamp without time zone, in_end timestamp without time zone)
      </title>
      <titleabbrev id="public.function.months-passed-in-start-timestamp-without-time-zone-in-end-timestamp-without-time-zone-titleabbrev">
       months_passed(in_start timestamp without time zone, in_end timestamp without time zone)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the number of months between in_start and in_end.
        <programlisting>

-- The addition of one day is so that it will return &#39;1&#39; when run on the end
-- day of consecutive months.

select (extract (months from age($2 + &#39;1 day&#39;, $1 + &#39;1 day&#39;))
       + extract (years from age($2, $1)) * 12)::int;
</programlisting>
      </para>
    </section>

<!-- Function next_leap_year_calc(in_date date, is_end boolean) -->
    <section id="public.function.next-leap-year-calc-in-date-date-is-end-boolean"
             xreflabel="()">
      <title id="public.function.next-leap-year-calc-in-date-date-is-end-boolean-title">
       next_leap_year_calc(in_date date, is_end boolean)
      </title>
      <titleabbrev id="public.function.next-leap-year-calc-in-date-date-is-end-boolean-titleabbrev">
       next_leap_year_calc(in_date date, is_end boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Next relevant leap year calculation for a daily depreciation calculation
        <programlisting>
SELECT
          (CASE WHEN extract(&#39;doy&#39; FROM $1) &lt; 59
          THEN extract(&#39;year&#39; FROM $1)
          ELSE extract(&#39;year&#39; FROM $1) + 1
          END)::int
          -
          CASE WHEN $2 THEN 1 ELSE 0 END;
</programlisting>
      </para>
    </section>

<!-- Function order__combine(in_ids integer[]) -->
    <section id="public.function.order-combine-in-ids-integerARRAY"
             xreflabel="()">
      <title id="public.function.order-combine-in-ids-integerARRAY-title">
       order__combine(in_ids integer[])
      </title>
      <titleabbrev id="public.function.order-combine-in-ids-integerARRAY-titleabbrev">
       order__combine(in_ids integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF oe</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

DECLARE retval oe;
        ordercount int;
        ids int[];
        loop_info record;
        settings text[];
        my_person_id int;
BEGIN

SELECT id INTO my_person_id
  FROM person
 WHERE entity_id = person__get_my_entity_id();

settings := ARRAY[&#39;sonumber&#39;, &#39;ponumber&#39;, &#39;sqnumber&#39;, &#39;rfqnumber&#39;];
ids := array[]::int[];

-- This approach of looping through insert/select operations will break down
-- if overly complex order consolidation jobs are run (think, hundreds of
-- combined orders in the *output*
--
-- The tradeoff is that if we address the huge complex runs here, then we have
-- the possibility of having to lock the whole table which poses other issues.
-- For that reason, I am going with this approach for now. --CT

FOR loop_info IN
       SELECT max(id) as id, taxincluded, entity_credit_account, oe_class_id,
              curr
         FROM oe WHERE id = any(in_ids)
     GROUP BY taxincluded, entity_credit_account, oe_class_id, curr
LOOP

INSERT INTO oe
       (ordnumber, transdate,   amount,        netamount,
        reqdate,   taxincluded, shippingpoint, notes,
        curr,      person_id,   closed,        quotation,
        quonumber, intnotes,    shipvia,       language_code,
        ponumber,  terms,       oe_class_id,   entity_credit_account)
SELECT CASE WHEN oe_class_id IN (1, 2)
            THEN setting_increment(settings[oe_class_id])
            ELSE NULL
        END,          now()::date,        sum(amount),        sum(netamount),
        min(reqdate), taxincluded,        min(shippingpoint), &#39;&#39;,
        curr,         my_person_id, false, false,
        CASE WHEN oe_class_id IN (3, 4)
            THEN setting_increment(settings[oe_class_id])
            ELSE NULL
        END,          NULL,      NULL,          NULL,
        null,       min(terms),  oe_class_id,  entity_credit_account
  FROM oe
 WHERE id = any (in_ids)
       AND taxincluded = loop_info.taxincluded
       AND entity_credit_account = loop_info.entity_credit_account
       AND oe_class_id = loop_info.oe_class_id
 GROUP BY curr, taxincluded, oe_class_id, entity_credit_account;


INSERT INTO orderitems
       (trans_id,      parts_id,        description,         qty,
        sellprice,     precision,       discount,            unit,
        reqdate,       ship,            serialnumber,        notes)
SELECT currval(&#39;oe_id_seq&#39;), oi.parts_id, oi.description,     oi.qty,
       oi.sellprice,   oi.precision,    oi.discount,         oi.unit,
       oi.reqdate,     oi.ship,         oi.serialnumber,     oi.notes
  FROM orderitems oi
  JOIN oe ON oi.trans_id = oe.id
 WHERE oe.id = any (in_ids)
       AND taxincluded = loop_info.taxincluded
       AND entity_credit_account = loop_info.entity_credit_account
       AND oe_class_id = loop_info.oe_class_id;

ids := ids || currval(&#39;oe_id_seq&#39;)::int;

END LOOP;

UPDATE oe SET closed = true WHERE id = any(in_ids);

FOR retval IN select * from oe WHERE id =any(ids)
LOOP
   RETURN NEXT retval;
END LOOP;

END;
</programlisting>
      </para>
    </section>

<!-- Function order__search(in_oe_class_id integer, in_meta_number text, in_legal_name text, in_ponumber text, in_ordnumber text, in_open boolean, in_closed boolean, in_shipvia text, in_description text, in_date_from date, in_date_to date, in_shippable boolean, in_buisness_units integer[]) -->
    <section id="public.function.order-search-in-oe-class-id-integer-in-meta-number-text-in-legal-name-text-in-ponumber-text-in-ordnumber-text-in-open-boolean-in-closed-boolean-in-shipvia-text-in-description-text-in-date-from-date-in-date-to-date-in-shippable-boolean-in-buisness-units-integerARRAY"
             xreflabel="()">
      <title id="public.function.order-search-in-oe-class-id-integer-in-meta-number-text-in-legal-name-text-in-ponumber-text-in-ordnumber-text-in-open-boolean-in-closed-boolean-in-shipvia-text-in-description-text-in-date-from-date-in-date-to-date-in-shippable-boolean-in-buisness-units-integerARRAY-title">
       order__search(in_oe_class_id integer, in_meta_number text, in_legal_name text, in_ponumber text, in_ordnumber text, in_open boolean, in_closed boolean, in_shipvia text, in_description text, in_date_from date, in_date_to date, in_shippable boolean, in_buisness_units integer[])
      </title>
      <titleabbrev id="public.function.order-search-in-oe-class-id-integer-in-meta-number-text-in-legal-name-text-in-ponumber-text-in-ordnumber-text-in-open-boolean-in-closed-boolean-in-shipvia-text-in-description-text-in-date-from-date-in-date-to-date-in-shippable-boolean-in-buisness-units-integerARRAY-titleabbrev">
       order__search(in_oe_class_id integer, in_meta_number text, in_legal_name text, in_ponumber text, in_ordnumber text, in_open boolean, in_closed boolean, in_shipvia text, in_description text, in_date_from date, in_date_to date, in_shippable boolean, in_buisness_units integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF order_search_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

       SELECT o.id,
              CASE WHEN oe_class_id IN (1, 2) THEN o.ordnumber
                   WHEN oe_class_id IN (3, 4) THEN o.quonumber
                   ELSE NULL
               END as ordnumber, o.transdate, o.reqdate,
              o.amount, c.name, o.netamount,
              o.entity_credit_account, o.closed, o.quonumber, o.shippingpoint,
              CASE WHEN ct.entity_class = 2 THEN ex.buy ELSE ex.sell END
              AS exchangerate, o.shipvia, pe.first_name || &#39; &#39; || pe.last_name
              AS employee, pm.first_name || &#39; &#39; || pm.last_name AS manager,
              o.curr, o.ponumber, ct.meta_number, c.id
         FROM oe o
         JOIN entity_credit_account ct ON (o.entity_credit_account = ct.id)
         JOIN entity c ON (c.id = ct.entity_id)
    LEFT JOIN person pe ON (o.person_id = pe.id)
    LEFT JOIN entity_employee e ON (pe.entity_id = e.entity_id)
    LEFT JOIN person pm ON (e.manager_id = pm.id)
    LEFT JOIN entity_employee m ON (pm.entity_id = m.entity_id)
    LEFT JOIN exchangerate ex
              ON (ex.curr = o.curr AND ex.transdate = o.transdate)
        WHERE o.oe_class_id = in_oe_class_id
             AND (in_meta_number IS NULL
                   or ct.meta_number ILIKE in_meta_number || &#39;%&#39;)
             AND (in_legal_name IS NULL OR
                     c.name @@ plainto_tsquery(in_legal_name))
             AND (in_ponumber IS NULL OR o.ponumber ILIKE in_ponumber || &#39;%&#39;)
            AND (in_ordnumber IS NULL
                     OR o.ordnumber ILIKE in_ordnumber || &#39;%&#39;)
             AND ((in_open is true and o.closed is false)
                 OR (in_closed is true and o.closed is true))
             AND (in_shipvia IS NULL
                      OR o.shipvia @@ plainto_tsquery(in_shipvia))
             AND (in_description IS NULL AND in_shippable IS NULL OR
                     EXISTS (SELECT 1
                               FROM orderitems oi
                               JOIN parts p ON p.id = oi.parts_id
                              WHERE trans_id = o.id
                                    AND (in_description IS NULL OR
                                        oi.description
                                        @@ plainto_tsquery(in_description))
                                    AND (in_shippable IS NULL OR
                                         p.assembly OR
                                         p.inventory_accno_id IS NOT NULL))
                 )
             AND (in_date_from IS NULL OR o.transdate &gt;= in_date_from)
             AND (in_date_to IS NULL OR o.transdate &lt;= in_date_to);

</programlisting>
      </para>
    </section>

<!-- Function overpayment__reverse(in_id integer, in_transdate date, in_batch_id integer, in_account_class integer, in_exchangerate numeric, in_curr bpchar) -->
    <section id="public.function.overpayment-reverse-in-id-integer-in-transdate-date-in-batch-id-integer-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar"
             xreflabel="()">
      <title id="public.function.overpayment-reverse-in-id-integer-in-transdate-date-in-batch-id-integer-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar-title">
       overpayment__reverse(in_id integer, in_transdate date, in_batch_id integer, in_account_class integer, in_exchangerate numeric, in_curr bpchar)
      </title>
      <titleabbrev id="public.function.overpayment-reverse-in-id-integer-in-transdate-date-in-batch-id-integer-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar-titleabbrev">
       overpayment__reverse(in_id integer, in_transdate date, in_batch_id integer, in_account_class integer, in_exchangerate numeric, in_curr bpchar)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
declare t_id int;
        in_cash_accno text;
BEGIN

-- reverse overpayment gl

INSERT INTO gl (transdate, reference, description, approved)
SELECT transdate, reference || &#39;-reversal&#39;, &#39;reversal of &#39; || description, &#39;0&#39;
  FROM gl WHERE id = (select gl_id from payment where id = in_id);

IF NOT FOUND THEN
   RETURN FALSE;
END IF;

t_id := currval(&#39;id&#39;);

INSERT INTO voucher (batch_id, trans_id, batch_class)
VALUES (in_batch_id, t_id, CASE WHEN in_account_class = 1 THEN 4 ELSE 7 END);

INSERT INTO acc_trans (transdate, trans_id, chart_id, amount)
SELECT in_transdate, t_id, chart_id, amount * -1
  FROM acc_trans
 WHERE trans_id = in_id;

-- reverse overpayment usage
PERFORM payment__reverse(ac.source, ac.transdate, eca.id, at.accno,
        in_transdate, eca.entity_class, in_batch_id, null,
        in_exchangerate, in_curr)
  FROM acc_trans ac
  JOIN account at ON ac.chart_id = at.id
  JOIN account_link al ON at.id = al.account_id AND al.description like &#39;A%paid&#39;
  JOIN (select id, entity_credit_account FROM ar UNION
        select id, entity_credit_account from ap) a ON a.id = ac.trans_id
  JOIN entity_credit_account eca ON a.entity_credit_account = eca.id
  JOIN payment_links pl ON pl.entry_id = ac.entry_id
  JOIN overpayments op ON op.payment_id = pl.payment_id
  JOIN payment p ON p.id = op.payment_id
 WHERE p.gl_id = in_id
GROUP BY ac.source, ac.transdate, eca.id, eca.entity_class,
         at.accno, al.description;

RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function parse_date(in_date date) -->
    <section id="public.function.parse-date-in-date-date"
             xreflabel="()">
      <title id="public.function.parse-date-in-date-date-title">
       parse_date(in_date date)
      </title>
      <titleabbrev id="public.function.parse-date-in-date-date-titleabbrev">
       parse_date(in_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>date</seg>
        </seglistitem>
       </segmentedlist>
 
        Simple way to cast a Perl string to a
date format of known type. 
        <programlisting> select $1; </programlisting>
      </para>
    </section>

<!-- Function part__get_by_id(in_id integer) -->
    <section id="public.function.part-get-by-id-in-id-integer"
             xreflabel="()">
      <title id="public.function.part-get-by-id-in-id-integer-title">
       part__get_by_id(in_id integer)
      </title>
      <titleabbrev id="public.function.part-get-by-id-in-id-integer-titleabbrev">
       part__get_by_id(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
select * from parts where id = $1;
</programlisting>
      </para>
    </section>

<!-- Function parts__get_by_id(in_id integer) -->
    <section id="public.function.parts-get-by-id-in-id-integer"
             xreflabel="()">
      <title id="public.function.parts-get-by-id-in-id-integer-title">
       parts__get_by_id(in_id integer)
      </title>
      <titleabbrev id="public.function.parts-get-by-id-in-id-integer-titleabbrev">
       parts__get_by_id(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM parts WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function parts__get_by_partnumber(in_partnumber text) -->
    <section id="public.function.parts-get-by-partnumber-in-partnumber-text"
             xreflabel="()">
      <title id="public.function.parts-get-by-partnumber-in-partnumber-text-title">
       parts__get_by_partnumber(in_partnumber text)
      </title>
      <titleabbrev id="public.function.parts-get-by-partnumber-in-partnumber-text-titleabbrev">
       parts__get_by_partnumber(in_partnumber text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM parts where partnumber = $1 AND NOT OBSOLETE;
</programlisting>
      </para>
    </section>

<!-- Function parts__search_lite(in_partnumber text, in_description text) -->
    <section id="public.function.parts-search-lite-in-partnumber-text-in-description-text"
             xreflabel="()">
      <title id="public.function.parts-search-lite-in-partnumber-text-in-description-text-title">
       parts__search_lite(in_partnumber text, in_description text)
      </title>
      <titleabbrev id="public.function.parts-search-lite-in-partnumber-text-in-description-text-titleabbrev">
       parts__search_lite(in_partnumber text, in_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT *
  FROM parts
 WHERE ($1 IS NULL OR (partnumber like $1 || &#39;%&#39;))
       AND ($2 IS NULL OR plainto_tsquery(get_default_lang()::regconfig, $2)
                          =
                          plainto_tsquery(get_default_lang()::regconfig, &#39;&#39;)
            OR (description
                @@
                plainto_tsquery(get_default_lang()::regconfig, $2)))
       AND not obsolete
ORDER BY partnumber;
</programlisting>
      </para>
    </section>

<!-- Function partsgroup__search(in_pricegroup text) -->
    <section id="public.function.partsgroup-search-in-pricegroup-text"
             xreflabel="()">
      <title id="public.function.partsgroup-search-in-pricegroup-text-title">
       partsgroup__search(in_pricegroup text)
      </title>
      <titleabbrev id="public.function.partsgroup-search-in-pricegroup-text-titleabbrev">
       partsgroup__search(in_pricegroup text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF partsgroup</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
  SELECT * FROM partsgroup
   WHERE $1 is null or partsgroup ilike $1 || &#39;%&#39;
ORDER BY partsgroup;
</programlisting>
      </para>
    </section>

<!-- Function payment__get_gl(in_payment_id integer) -->
    <section id="public.function.payment-get-gl-in-payment-id-integer"
             xreflabel="()">
      <title id="public.function.payment-get-gl-in-payment-id-integer-title">
       payment__get_gl(in_payment_id integer)
      </title>
      <titleabbrev id="public.function.payment-get-gl-in-payment-id-integer-titleabbrev">
       payment__get_gl(in_payment_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>gl</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM gl WHERE id = (select id from payment where id = $1);
</programlisting>
      </para>
    </section>

<!-- Function payment__overpayments_list(in_date_from date, in_date_to date, in_control_code text, in_meta_number text, in_name_part text) -->
    <section id="public.function.payment-overpayments-list-in-date-from-date-in-date-to-date-in-control-code-text-in-meta-number-text-in-name-part-text"
             xreflabel="()">
      <title id="public.function.payment-overpayments-list-in-date-from-date-in-date-to-date-in-control-code-text-in-meta-number-text-in-name-part-text-title">
       payment__overpayments_list(in_date_from date, in_date_to date, in_control_code text, in_meta_number text, in_name_part text)
      </title>
      <titleabbrev id="public.function.payment-overpayments-list-in-date-from-date-in-date-to-date-in-control-code-text-in-meta-number-text-in-name-part-text-titleabbrev">
       payment__overpayments_list(in_date_from date, in_date_to date, in_control_code text, in_meta_number text, in_name_part text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF overpayment_list_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
-- I don&#39;t like the subquery below but we are looking for the first line, and
-- I can&#39;t think of a better way to do that. --CT

-- This should never hit an income statement-side account but I have handled it
-- in case of configuration error. --CT
SELECT o.payment_id, e.name, o.available, g.transdate,
       (select amount * CASE WHEN c.category in (&#39;A&#39;, &#39;E&#39;) THEN -1 ELSE 1 END
          from acc_trans
         where g.id = trans_id
               AND chart_id = o.chart_id ORDER BY entry_id ASC LIMIT 1) as amount
  FROM overpayments o
  JOIN payment p ON o.payment_id = p.id
  JOIN gl g ON g.id = p.gl_id
  JOIN account c ON c.id = o.chart_id
  JOIN entity_credit_account eca ON eca.id = o.entity_credit_id
  JOIN entity e ON eca.entity_id = e.id
 WHERE ($1 IS NULL OR $1 &lt;= g.transdate) AND
       ($2 IS NULL OR $2 &gt;= g.transdate) AND
       ($3 IS NULL OR $3 = e.control_code) AND
       ($4 IS NULL OR $4 = eca.meta_number) AND
       ($5 IS NULL OR e.name @@ plainto_tsquery($5));
</programlisting>
      </para>
    </section>

<!-- Function payment__reverse(in_source text, in_date_paid date, in_credit_id integer, in_cash_accno text, in_date_reversed date, in_account_class integer, in_batch_id integer, in_voucher_id integer, in_exchangerate numeric, in_currency bpchar) -->
    <section id="public.function.payment-reverse-in-source-text-in-date-paid-date-in-credit-id-integer-in-cash-accno-text-in-date-reversed-date-in-account-class-integer-in-batch-id-integer-in-voucher-id-integer-in-exchangerate-numeric-in-currency-bpchar"
             xreflabel="()">
      <title id="public.function.payment-reverse-in-source-text-in-date-paid-date-in-credit-id-integer-in-cash-accno-text-in-date-reversed-date-in-account-class-integer-in-batch-id-integer-in-voucher-id-integer-in-exchangerate-numeric-in-currency-bpchar-title">
       payment__reverse(in_source text, in_date_paid date, in_credit_id integer, in_cash_accno text, in_date_reversed date, in_account_class integer, in_batch_id integer, in_voucher_id integer, in_exchangerate numeric, in_currency bpchar)
      </title>
      <titleabbrev id="public.function.payment-reverse-in-source-text-in-date-paid-date-in-credit-id-integer-in-cash-accno-text-in-date-reversed-date-in-account-class-integer-in-batch-id-integer-in-voucher-id-integer-in-exchangerate-numeric-in-currency-bpchar-titleabbrev">
       payment__reverse(in_source text, in_date_paid date, in_credit_id integer, in_cash_accno text, in_date_reversed date, in_account_class integer, in_batch_id integer, in_voucher_id integer, in_exchangerate numeric, in_currency bpchar)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
Reverses a payment.  All fields are mandatory except batch_id and voucher_id
because they determine the identity of the payment to be reversed.

        <programlisting>
DECLARE
        pay_row record;
        t_voucher_id int;
        t_voucher_inserted bool;
        t_currs text[];
        t_rev_fx numeric;
        t_fxgain_id int;
        t_fxloss_id int;
        t_paid_fx numeric;
BEGIN
        SELECT * INTO t_rev_fx FROM currency_get_exchangerate(
              in_currency, in_date_reversed, in_account_class);

        SELECT * INTO t_paid_fx FROM currency_get_exchangerate(
              in_currency, in_date_paid, in_account_class);

       select value::int INTO t_fxgain_id FROM setting_get(&#39;fxgain_accno_id&#39;);
       select value::int INTO t_fxloss_id FROM setting_get(&#39;fxloss_accno_id&#39;);

       SELECT string_to_array(value, &#39;:&#39;) into t_currs
          from defaults
         where setting_key = &#39;curr&#39;;

        IF in_currency IS NULL OR in_currency = t_currs[1] THEN
                t_rev_fx := 1;
                t_paid_fx := 1;
        ELSIF t_rev_fx IS NULL THEN
                t_rev_fx := in_exchangerate;
                PERFORM payments_set_exchangerate(in_account_class,
                                                  in_exchangerate,
                                                  in_currency,
                                                  in_date_reversed);
        ELSIF t_rev_fx &lt;&gt; in_exchangerate THEN
                RAISE EXCEPTION &#39;Exchange rate different than on file&#39;;
        END IF;
        IF t_rev_fx IS NULL THEN
            RAISE EXCEPTION &#39;No exchangerate provided and not default currency&#39;;
        END IF;


        IF in_batch_id IS NOT NULL THEN
                t_voucher_id := nextval(&#39;voucher_id_seq&#39;);
                t_voucher_inserted := FALSE;
        END IF;
        FOR pay_row IN
                SELECT a.*, c.ar_ap_account_id, arap.curr, arap.fxrate
                FROM acc_trans a
                JOIN (select id, curr, entity_credit_account,
                             CASE WHEN curr = t_currs[1] THEN 1
                                   ELSE buy END as fxrate
                        FROM ar
                   LEFT JOIN exchangerate USING (transdate, curr)
                       WHERE in_account_class = 2
                        UNION
                        SELECT id, curr, entity_credit_account,
                               CASE WHEN curr = t_currs[1] THEN 1
                                    ELSE sell END as fxrate
                        FROM ap
                   LEFT JOIN exchangerate USING (transdate, curr)
                       WHERE in_account_class = 1
                ) arap ON (a.trans_id = arap.id)
                JOIN entity_credit_account c
                        ON (arap.entity_credit_account = c.id)
                JOIN account ch ON (a.chart_id = ch.id)
                WHERE coalesce(a.source, &#39;&#39;) = coalesce(in_source, &#39;&#39;)
                        AND a.transdate = in_date_paid
                        AND in_credit_id = arap.entity_credit_account
                        AND in_cash_accno = ch.accno
                        and in_voucher_id IS NOT DISTINCT FROM voucher_id
        LOOP
                IF pay_row.curr = t_currs[1] THEN
                   pay_row.fxrate = 1;
                END IF;

                IF in_batch_id IS NOT NULL
                        AND t_voucher_inserted IS NOT TRUE
                THEN
                        INSERT INTO voucher
                        (id, trans_id, batch_id, batch_class)
                        VALUES
                        (t_voucher_id, pay_row.trans_id, in_batch_id,
                                CASE WHEN in_account_class = 1 THEN 4
                                     WHEN in_account_class = 2 THEN 7
                                END);

                        t_voucher_inserted := TRUE;
                END IF;

                INSERT INTO acc_trans
                (trans_id, chart_id, amount, transdate, source, memo, approved,
                        voucher_id)
                VALUES
                (pay_row.trans_id, pay_row.chart_id,
                        pay_row.amount / t_paid_fx * -1 * t_rev_fx,
                        in_date_reversed, in_source, &#39;Reversing &#39; ||
                        COALESCE(in_source, &#39;&#39;),
                        case when in_batch_id is not null then false
                        else true end, t_voucher_id),
                 (pay_row.trans_id, pay_row.ar_ap_account_id,
                        pay_row.amount / t_paid_fx * pay_row.fxrate,
                        in_date_reversed, in_source, &#39;Reversing &#39; ||
                        COALESCE(in_source, &#39;&#39;),
                        case when in_batch_id is not null then false
                        else true end, t_voucher_id),
                 (pay_row.trans_id,
                  case when pay_row.fxrate &gt; t_rev_fx
                       THEN t_fxloss_id ELSE t_fxgain_id END,
                  pay_row.amount / t_paid_fx * (t_rev_fx - pay_row.fxrate),
                  in_date_reversed, in_source, &#39;Reversing &#39; ||
                                                COALESCE(in_source, &#39;&#39;),
                   case when in_batch_id is not null then false
                        else true end, t_voucher_id);


        END LOOP;
        RETURN 1;
END;
</programlisting>
      </para>
    </section>

<!-- Function payment__search(in_source text, in_from_date date, in_to_date date, in_credit_id integer, in_cash_accno text, in_entity_class integer, in_currency bpchar, in_meta_number text) -->
    <section id="public.function.payment-search-in-source-text-in-from-date-date-in-to-date-date-in-credit-id-integer-in-cash-accno-text-in-entity-class-integer-in-currency-bpchar-in-meta-number-text"
             xreflabel="()">
      <title id="public.function.payment-search-in-source-text-in-from-date-date-in-to-date-date-in-credit-id-integer-in-cash-accno-text-in-entity-class-integer-in-currency-bpchar-in-meta-number-text-title">
       payment__search(in_source text, in_from_date date, in_to_date date, in_credit_id integer, in_cash_accno text, in_entity_class integer, in_currency bpchar, in_meta_number text)
      </title>
      <titleabbrev id="public.function.payment-search-in-source-text-in-from-date-date-in-to-date-date-in-credit-id-integer-in-cash-accno-text-in-entity-class-integer-in-currency-bpchar-in-meta-number-text-titleabbrev">
       payment__search(in_source text, in_from_date date, in_to_date date, in_credit_id integer, in_cash_accno text, in_entity_class integer, in_currency bpchar, in_meta_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_record</seg>
        </seglistitem>
       </segmentedlist>
 
       This searches for payments.  in_date_to and _date_from specify the acceptable
date range.  All other matches are exact except that null matches all values.

Currently (and to support earlier data) we define a payment as a collection of
acc_trans records against the same credit account and cash account, on the same
day with the same source number, and optionally the same voucher id.
        <programlisting>
                select sum(CASE WHEN c.entity_class = 1 then a.amount
                                ELSE a.amount * -1 END), c.meta_number,
                        c.id, e.name as legal_name,
                        compound_array(ARRAY[ARRAY[ch.id::text, ch.accno,
                                ch.description]]), a.source,
                        b.control_code, b.description, a.voucher_id, a.transdate
                FROM entity_credit_account c
                JOIN ( select entity_credit_account, id, curr, approved
                        FROM ar WHERE in_entity_class = 2
                        UNION
                        SELECT entity_credit_account, id, curr, approved
                        FROM ap WHERE in_entity_class = 1
                        ) arap ON (arap.entity_credit_account = c.id)
                JOIN acc_trans a ON (arap.id = a.trans_id)
                JOIN account ch ON (ch.id = a.chart_id)
                JOIN entity e ON (c.entity_id = e.id)
                LEFT JOIN voucher v ON (v.id = a.voucher_id)
                LEFT JOIN batch b ON (b.id = v.batch_id)
                WHERE ((ch.accno = in_cash_accno
                        OR (in_cash_accno IS NULL
                            AND ch.id IN (select account_id
                                            FROM account_link
                                           WHERE description IN(&#39;AR_paid&#39;,
                                                                &#39;AP_paid&#39;)))))
                      AND (in_currency IS NULL OR in_currency = arap.curr)
                      AND (c.id = in_credit_id OR in_credit_id IS NULL)
                      AND (a.transdate &gt;= in_from_date
                              OR in_from_date IS NULL)
                      AND (a.transdate &lt;= in_to_date OR in_to_date IS NULL)
                      AND (source = in_source OR in_source IS NULL)
                      AND arap.approved AND a.approved
                      AND (c.meta_number = in_meta_number
                              OR in_meta_number IS NULL)
                GROUP BY c.meta_number, c.id, e.name, a.transdate,
                        a.source, a.memo, b.id, b.control_code, b.description,
                        voucher_id
                ORDER BY a.transdate, c.meta_number, a.source;
</programlisting>
      </para>
    </section>

<!-- Function payment_bulk_post(in_transactions numeric[], in_batch_id integer, in_source text, in_total numeric, in_ar_ap_accno text, in_cash_accno text, in_payment_date date, in_account_class integer, in_exchangerate numeric, in_currency text) -->
    <section id="public.function.payment-bulk-post-in-transactions-numericARRAY-in-batch-id-integer-in-source-text-in-total-numeric-in-ar-ap-accno-text-in-cash-accno-text-in-payment-date-date-in-account-class-integer-in-exchangerate-numeric-in-currency-text"
             xreflabel="()">
      <title id="public.function.payment-bulk-post-in-transactions-numericARRAY-in-batch-id-integer-in-source-text-in-total-numeric-in-ar-ap-accno-text-in-cash-accno-text-in-payment-date-date-in-account-class-integer-in-exchangerate-numeric-in-currency-text-title">
       payment_bulk_post(in_transactions numeric[], in_batch_id integer, in_source text, in_total numeric, in_ar_ap_accno text, in_cash_accno text, in_payment_date date, in_account_class integer, in_exchangerate numeric, in_currency text)
      </title>
      <titleabbrev id="public.function.payment-bulk-post-in-transactions-numericARRAY-in-batch-id-integer-in-source-text-in-total-numeric-in-ar-ap-accno-text-in-cash-accno-text-in-payment-date-date-in-account-class-integer-in-exchangerate-numeric-in-currency-text-titleabbrev">
       payment_bulk_post(in_transactions numeric[], in_batch_id integer, in_source text, in_total numeric, in_ar_ap_accno text, in_cash_accno text, in_payment_date date, in_account_class integer, in_exchangerate numeric, in_currency text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        This posts the payments for large batch workflows.

Note that in_transactions is a two-dimensional numeric array.  Of each
sub-array, the first element is the (integer) transaction id, and the second
is the amount for that transaction.  
        <programlisting>
DECLARE
        out_count int;
        t_voucher_id int;
        t_trans_id int;
        t_amount numeric;
        t_ar_ap_id int;
        t_cash_id int;
        t_currs text[];
        t_exchangerate numeric;
        t_cash_sign int;
        t_batch batch;
BEGIN

        SELECT * INTO t_exchangerate FROM currency_get_exchangerate(
              in_currency, in_payment_date, in_account_class);

        IF in_batch_id IS NULL THEN
                -- t_voucher_id := NULL;
                RAISE EXCEPTION &#39;Bulk Post Must be from Batch!&#39;;
        ELSE
                SELECT * INTO t_batch FROM batch WHERE in_batch_id = id;
                IF t_batch.approved_by IS NOT NULL THEN
                    RAISE EXCEPTION &#39;Approved Batch&#39;;
                ELSIF t_batch.locked_by IS NOT NULL THEN
                    PERFORM * FROM session
                       JOIN users ON (session.users_id = users.id)
                      WHERE session_id = t_batch.locked_by
                            AND users.username = SESSION_USER;

                    IF NOT FOUND THEN
                        -- locked by someone else
                        RAISE EXCEPTION &#39;batch locked by %, I am %&#39;, t_batch.locked_by, session_user;
                    END IF;
                END IF;
                INSERT INTO voucher (batch_id, batch_class, trans_id)
                values (in_batch_id,
                (SELECT batch_class_id FROM batch WHERE id = in_batch_id),
                in_transactions[1][1]);

                t_voucher_id := currval(&#39;voucher_id_seq&#39;);
        END IF;

        SELECT string_to_array(value, &#39;:&#39;) into t_currs
          from defaults
         where setting_key = &#39;curr&#39;;

        IF (in_currency IS NULL OR in_currency = t_currs[1]) THEN
                t_exchangerate := 1;
        ELSIF t_exchangerate IS NULL THEN
                t_exchangerate := in_exchangerate;
                PERFORM payments_set_exchangerate(in_account_class,
                                                  in_exchangerate,
                                                  in_currency,
                                                  in_payment_date);
        ELSIF t_exchangerate &lt;&gt; in_exchangerate THEN
                RAISE EXCEPTION &#39;Exchange rate different than on file&#39;;
        END IF;
        IF t_exchangerate IS NULL THEN
            RAISE EXCEPTION &#39;No exchangerate provided and not default currency&#39;;
        END IF;

        CREATE TEMPORARY TABLE bulk_payments_in
           (id int, amount numeric, fxrate numeric, gain_loss_accno int);

        select id into t_ar_ap_id from chart where accno = in_ar_ap_accno;
        select id into t_cash_id from chart where accno = in_cash_accno;

        FOR out_count IN
                        array_lower(in_transactions, 1) ..
                        array_upper(in_transactions, 1)
        LOOP
            -- Fill the bulk payments table
            INSERT INTO bulk_payments_in(id, amount)
            VALUES (in_transactions[out_count][1],
                    in_transactions[out_count][2]);
        END LOOP;

        IF in_account_class = 1 THEN
            t_cash_sign := 1;
        ELSE
            t_cash_sign := -1;
        END IF;

        IF (in_currency IS NULL OR in_currency = t_currs[1]) THEN
            UPDATE bulk_payments_in
               SET fxrate = 1;
        ELSE
            UPDATE bulk_payments_in
               SET fxrate =
                (SELECT CASE WHEN in_account_class = 1 THEN sell
                             ELSE buy
                        END
                   FROM exchangerate e
                   JOIN (SELECT transdate, id, curr FROM ar
                         UNION
                         SELECT transdate, id, curr FROM ap) a
                     ON (e.transdate = a.transdate
                         AND e.curr = a.curr)
                   WHERE a.id = bulk_payments_in.id);
            UPDATE bulk_payments_in
               SET gain_loss_accno =
                (SELECT value::int FROM defaults
                  WHERE setting_key = &#39;fxgain_accno_id&#39;)
             WHERE ((t_exchangerate - bulk_payments_in.fxrate) * t_cash_sign) &lt; 0;
            UPDATE bulk_payments_in
               SET gain_loss_accno = (SELECT value::int FROM defaults
                  WHERE setting_key = &#39;fxloss_accno_id&#39;)
             WHERE ((t_exchangerate - bulk_payments_in.fxrate) * t_cash_sign) &gt; 0;
            -- explicitly leave zero gain/loss accno_id entries at NULL
            -- so we have an easy check for which
        END IF;

        -- Insert cash side
        INSERT INTO acc_trans
             (trans_id, chart_id, amount, approved,
              voucher_id, transdate, source)
           SELECT id, t_cash_id, amount * t_cash_sign * t_exchangerate/fxrate,
                  CASE WHEN t_voucher_id IS NULL THEN true
                       ELSE false END,
                  t_voucher_id, in_payment_date, in_source
             FROM bulk_payments_in  where amount &lt;&gt; 0;

        -- early payment discounts
        IF t_cash_sign IS NULL THEN
             raise exception &#39;t_cash_sign is null&#39;;
        ELSIF t_exchangerate IS NULL THEN
             raise exception &#39;t_exchangerate is null&#39;;
        END IF;
        INSERT INTO acc_trans
               (trans_id, chart_id, amount, approved,
               voucher_id, transdate, source)
        SELECT bpi.id, eca.discount_account_id,
               amount * t_cash_sign * t_exchangerate/fxrate
               / (1 - discount::numeric/100)
               * (discount::numeric/100),
               CASE WHEN t_voucher_id IS NULL THEN true
                       ELSE false END,
               t_voucher_id, in_payment_date, in_source
          FROM bulk_payments_in bpi
          JOIN (select entity_credit_account, id, transdate FROM ar
                 WHERE in_account_class = 2
                 UNION
                SELECT entity_credit_account, id, transdate FROM ap
                 WHERE in_account_class = 1) gl ON gl.id = bpi.id
          JOIN entity_credit_account eca ON gl.entity_credit_account = eca.id
         WHERE bpi.amount &lt;&gt; 0
               AND extract(&#39;days&#39; from age(gl.transdate)) &lt; eca.discount_terms
               and eca.discount_terms is not null AND discount IS NOT NULL
               AND eca.discount_account_id IS NOT NULL;

        INSERT INTO acc_trans
               (trans_id, chart_id, amount, approved,
               voucher_id, transdate, source)
        SELECT bpi.id, t_ar_ap_id,
               amount * t_cash_sign * -1 * t_exchangerate/fxrate
               / (1 - discount::numeric/100)
               * (discount::numeric/100),
               CASE WHEN t_voucher_id IS NULL THEN true
                       ELSE false END,
               t_voucher_id, in_payment_date, in_source
          FROM bulk_payments_in bpi
          JOIN (select entity_credit_account, id, transdate FROM ar
                 WHERE in_account_class = 2
                 UNION
                SELECT entity_credit_account, id, transdate FROM ap
                 WHERE in_account_class = 1) gl ON gl.id = bpi.id
          JOIN entity_credit_account eca ON gl.entity_credit_account = eca.id
         WHERE bpi.amount &lt;&gt; 0
               AND extract(&#39;days&#39; from age(gl.transdate)) &lt; eca.discount_terms
               AND eca.discount_terms IS NOT NULL AND discount IS NOT NULL
               AND eca.discount_account_id IS NOT NULL;

        -- Insert ar/ap side
        INSERT INTO acc_trans
             (trans_id, chart_id, amount, approved,
              voucher_id, transdate, source)
           SELECT id, t_ar_ap_id,
                  amount * -1 * t_cash_sign,
                  CASE WHEN t_voucher_id IS NULL THEN true
                       ELSE false END,
                  t_voucher_id, in_payment_date, in_source
             FROM bulk_payments_in where amount &lt;&gt; 0;

        -- Insert fx gain/loss effects, if applicable
        INSERT INTO acc_trans
             (trans_id, chart_id, amount, approved,
              voucher_id, transdate, source)
           SELECT id, gain_loss_accno,
                  amount * t_cash_sign * (1 - t_exchangerate/fxrate),
                  CASE WHEN t_voucher_id IS NULL THEN true
                       ELSE false END,
                  t_voucher_id, in_payment_date, in_source
             FROM bulk_payments_in
            WHERE amount &lt;&gt; 0 AND gain_loss_accno IS NOT NULL;

        DROP TABLE bulk_payments_in;
        perform unlock_all();
        return out_count;
END;
</programlisting>
      </para>
    </section>

<!-- Function payment_gather_header_info(in_account_class integer, in_payment_id integer) -->
    <section id="public.function.payment-gather-header-info-in-account-class-integer-in-payment-id-integer"
             xreflabel="()">
      <title id="public.function.payment-gather-header-info-in-account-class-integer-in-payment-id-integer-title">
       payment_gather_header_info(in_account_class integer, in_payment_id integer)
      </title>
      <titleabbrev id="public.function.payment-gather-header-info-in-account-class-integer-in-payment-id-integer-titleabbrev">
       payment_gather_header_info(in_account_class integer, in_payment_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_header_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This function finds a payment based on the id and retrieves the record,
it is usefull for printing payments :) 
        <programlisting>
   SELECT p.id as payment_id, p.reference as payment_reference, p.payment_date,
          c.legal_name as legal_name, am.amount as amount, em.first_name, em.last_name, p.currency, p.notes
   FROM payment p
   JOIN entity_employee ent_em ON (ent_em.entity_id = p.employee_id)
   JOIN person em ON (ent_em.entity_id = em.entity_id)
   JOIN entity_credit_account eca ON (eca.id = p.entity_credit_id)
   JOIN company c ON   (c.entity_id  = eca.entity_id)
   JOIN payment_links pl ON (p.id = pl.payment_id)
   LEFT JOIN (  SELECT sum(a.amount) as amount
                FROM acc_trans a
                JOIN account acc ON (a.chart_id = acc.id)
                JOIN account_link al ON (acc.id =al.account_id)
                JOIN payment_links pl ON (pl.entry_id=a.entry_id)
                WHERE al.description in
                       (&#39;AP_paid&#39;, &#39;AP_discount&#39;, &#39;AR_paid&#39;, &#39;AR_discount&#39;)
                       and ((in_account_class = 1 AND al.description like &#39;AP%&#39;)
                       or (in_account_class = 2 AND al.description like &#39;AR%&#39;))
             ) am ON (true)
   WHERE p.id = in_payment_id;
 </programlisting>
      </para>
    </section>

<!-- Function payment_gather_line_info(in_account_class integer, in_payment_id integer) -->
    <section id="public.function.payment-gather-line-info-in-account-class-integer-in-payment-id-integer"
             xreflabel="()">
      <title id="public.function.payment-gather-line-info-in-account-class-integer-in-payment-id-integer-title">
       payment_gather_line_info(in_account_class integer, in_payment_id integer)
      </title>
      <titleabbrev id="public.function.payment-gather-line-info-in-account-class-integer-in-payment-id-integer-titleabbrev">
       payment_gather_line_info(in_account_class integer, in_payment_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_line_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This function finds a payment based on the id and retrieves all the line records,
it is usefull for printing payments and build reports :) 
        <programlisting>
     SELECT pl.payment_id, ac.entry_id, pl.type as link_type, ac.trans_id, a.invnumber as invoice_number,
     ac.chart_id, ch.accno as chart_accno, ch.description as chart_description, ch.link as chart_link,
     ac.amount,  ac.transdate as trans_date, ac.source, ac.cleared, ac.fx_transaction,
     ac.memo, ac.invoice_id, ac.approved, ac.cleared_on, ac.reconciled_on
     FROM acc_trans ac
     JOIN payment_links pl ON (pl.entry_id = ac.entry_id )
     JOIN chart         ch ON (ch.id = ac.chart_id)
     LEFT JOIN (SELECT id,invnumber
                 FROM ar WHERE in_account_class = 2
                 UNION
                 SELECT id,invnumber
                 FROM ap WHERE in_account_class = 1
                ) a ON (ac.trans_id = a.id)
     WHERE pl.payment_id = in_payment_id;
 </programlisting>
      </para>
    </section>

<!-- Function payment_get_all_accounts(in_account_class integer) -->
    <section id="public.function.payment-get-all-accounts-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.payment-get-all-accounts-in-account-class-integer-title">
       payment_get_all_accounts(in_account_class integer)
      </title>
      <titleabbrev id="public.function.payment-get-all-accounts-in-account-class-integer-titleabbrev">
       payment_get_all_accounts(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_open_account</seg>
        </seglistitem>
       </segmentedlist>
 
        This function takes a single argument (1 for vendor, 2 for customer as
always) and returns all entities with accounts of the appropriate type. 
        <programlisting>
                SELECT  ec.id,
                        e.name, ec.entity_class
                FROM entity e
                JOIN entity_credit_account ec ON (ec.entity_id = e.id)
                                WHERE e.entity_class = in_account_class
</programlisting>
      </para>
    </section>

<!-- Function payment_get_all_contact_invoices(in_account_class integer, in_business_id integer, in_currency bpchar, in_date_from date, in_date_to date, in_batch_id integer, in_ar_ap_accno text, in_meta_number text) -->
    <section id="public.function.payment-get-all-contact-invoices-in-account-class-integer-in-business-id-integer-in-currency-bpchar-in-date-from-date-in-date-to-date-in-batch-id-integer-in-ar-ap-accno-text-in-meta-number-text"
             xreflabel="()">
      <title id="public.function.payment-get-all-contact-invoices-in-account-class-integer-in-business-id-integer-in-currency-bpchar-in-date-from-date-in-date-to-date-in-batch-id-integer-in-ar-ap-accno-text-in-meta-number-text-title">
       payment_get_all_contact_invoices(in_account_class integer, in_business_id integer, in_currency bpchar, in_date_from date, in_date_to date, in_batch_id integer, in_ar_ap_accno text, in_meta_number text)
      </title>
      <titleabbrev id="public.function.payment-get-all-contact-invoices-in-account-class-integer-in-business-id-integer-in-currency-bpchar-in-date-from-date-in-date-to-date-in-batch-id-integer-in-ar-ap-accno-text-in-meta-number-text-titleabbrev">
       payment_get_all_contact_invoices(in_account_class integer, in_business_id integer, in_currency bpchar, in_date_from date, in_date_to date, in_batch_id integer, in_ar_ap_accno text, in_meta_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_contact_invoice</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function takes the following arguments (all prefaced with in_ in the db):
account_class: 1 for vendor, 2 for customer
business_type: integer of business.id.
currency: char(3) of currency (for example &apos;USD&apos;)
date_from, date_to:  These dates are inclusive.
batch_id:  For payment batches, where fees are concerned.
ar_ap_accno:  The AR/AP account number.

This then returns a set of contact information with a 2 dimensional array
cnsisting of outstanding invoices.

Note that the payment selection logic is that this returns all invoices which are
either approved or in the batch_id specified.  It also locks the invoices using
the LedgerSMB discretionary locking framework, and if not possible, returns the
username of the individual who has the lock.

        <programlisting>
                  SELECT c.id AS contact_id, e.control_code as econtrol_code,
                        c.description as eca_description,
                        e.name AS contact_name,
                         c.meta_number AS account_number,
                         sum( case when u.username IS NULL or
                                       u.username = SESSION_USER
                             THEN
                              coalesce(p.due::numeric, 0) -
                              CASE WHEN c.discount_terms
                                        &gt; extract(&#39;days&#39; FROM age(a.transdate))
                                   THEN 0
                                   ELSE (coalesce(p.due::numeric, 0)) *
                                        coalesce(c.discount::numeric, 0) / 100
                              END
                             ELSE 0::numeric
                             END) AS total_due,
                         compound_array(ARRAY[[
                              a.id::text, a.invnumber, a.transdate::text,
                              a.amount::text, (a.amount - p.due)::text,
                              (CASE WHEN c.discount_terms
                                        &lt; extract(&#39;days&#39; FROM age(a.transdate))
                                   THEN 0
                                   ELSE (coalesce(p.due, 0) * coalesce(c.discount, 0) / 100)
                              END)::text,
                              (coalesce(p.due, 0) -
                              (CASE WHEN c.discount_terms
                                        &lt; extract(&#39;days&#39; FROM age(a.transdate))
                                   THEN 0
                                   ELSE (coalesce(p.due, 0)) * coalesce(c.discount, 0) / 100
                              END))::text,
                                case when u.username IS NOT NULL
                                          and u.username &lt;&gt; SESSION_USER
                                     THEN 0::text
                                     ELSE 1::text
                                END,
                                COALESCE(u.username, 0::text)
                                ]]),
                              sum(case when a.batch_id = in_batch_id then 1
                                  else 0 END),
                              bool_and(lock_record(a.id, (select max(session_id)
                                FROM &quot;session&quot; where users_id = (
                                        select id from users WHERE username =
                                        SESSION_USER))))

                    FROM entity e
                    JOIN entity_credit_account c ON (e.id = c.entity_id)
                    JOIN (SELECT ap.id, invnumber, transdate, amount, entity_id,
                                 curr, 1 as invoice_class,
                                 entity_credit_account, on_hold, v.batch_id,
                                 approved, paid
                            FROM ap
                       LEFT JOIN (select * from voucher where batch_class = 1) v
                                 ON (ap.id = v.trans_id)
                           WHERE in_account_class = 1
                                 AND (v.batch_class = 1 or v.batch_id IS NULL)
                           UNION
                          SELECT ar.id, invnumber, transdate, amount, entity_id,
                                 curr, 2 as invoice_class,
                                 entity_credit_account, on_hold, v.batch_id,
                                 approved, paid
                            FROM ar
                       LEFT JOIN (select * from voucher where batch_class = 2) v
                                 ON (ar.id = v.trans_id)
                           WHERE in_account_class = 2
                                 AND (v.batch_class = 2 or v.batch_id IS NULL)
                        ORDER BY transdate
                         ) a ON (a.entity_credit_account = c.id)
                    JOIN transactions t ON (a.id = t.id)
                    JOIN (SELECT acc_trans.trans_id,
                                 sum(CASE WHEN in_account_class = 1 THEN amount
                                          WHEN in_account_class = 2
                                          THEN amount * -1
                                     END) AS due
                            FROM acc_trans
                            JOIN account coa ON (coa.id = acc_trans.chart_id)
                            JOIN account_link al ON (al.account_id = coa.id)
                       LEFT JOIN voucher v ON (acc_trans.voucher_id = v.id)
                           WHERE ((al.description = &#39;AP&#39; AND in_account_class = 1)
                                 OR (al.description = &#39;AR&#39; AND in_account_class = 2))
                           AND (approved IS TRUE or v.batch_class IN (3, 6))
                        GROUP BY acc_trans.trans_id) p ON (a.id = p.trans_id)
                LEFT JOIN &quot;session&quot; s ON (s.&quot;session_id&quot; = t.locked_by)
                LEFT JOIN users u ON (u.id = s.users_id)
                   WHERE (a.batch_id = in_batch_id
                          OR (a.invoice_class = in_account_class
                             AND a.approved
                         AND due &lt;&gt; 0
                         AND NOT a.on_hold
                         AND a.curr = in_currency
                         AND EXISTS (select trans_id FROM acc_trans
                                      WHERE trans_id = a.id AND
                                            chart_id = (SELECT id from account
                                                         WHERE accno
                                                               = in_ar_ap_accno)
                                    )))
                         AND (in_meta_number IS NULL OR
                             in_meta_number = c.meta_number)
                GROUP BY c.id, e.name, c.meta_number, c.threshold,
                        e.control_code, c.description
                  HAVING  c.threshold is null or (sum(p.due) &gt;= c.threshold
                        OR sum(case when a.batch_id = in_batch_id then 1
                                  else 0 END) &gt; 0)
        ORDER BY c.meta_number ASC;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_available_overpayment_amount(in_account_class integer, in_entity_credit_id integer) -->
    <section id="public.function.payment-get-available-overpayment-amount-in-account-class-integer-in-entity-credit-id-integer"
             xreflabel="()">
      <title id="public.function.payment-get-available-overpayment-amount-in-account-class-integer-in-entity-credit-id-integer-title">
       payment_get_available_overpayment_amount(in_account_class integer, in_entity_credit_id integer)
      </title>
      <titleabbrev id="public.function.payment-get-available-overpayment-amount-in-account-class-integer-in-entity-credit-id-integer-titleabbrev">
       payment_get_available_overpayment_amount(in_account_class integer, in_entity_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_overpayments_available_amount</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
              SELECT chart_id, accno,   chart_description, available
              FROM overpayments
              WHERE payment_class  = in_account_class
              AND entity_credit_id = in_entity_credit_id
              AND available &lt;&gt; 0;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_entity_account_payment_info(in_entity_credit_id integer) -->
    <section id="public.function.payment-get-entity-account-payment-info-in-entity-credit-id-integer"
             xreflabel="()">
      <title id="public.function.payment-get-entity-account-payment-info-in-entity-credit-id-integer-title">
       payment_get_entity_account_payment_info(in_entity_credit_id integer)
      </title>
      <titleabbrev id="public.function.payment-get-entity-account-payment-info-in-entity-credit-id-integer-titleabbrev">
       payment_get_entity_account_payment_info(in_entity_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>payment_vc_info</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns payment information on the entity credit account as
  required to for discount calculations and payment processing. 
        <programlisting>
 SELECT ec.id, coalesce(ec.pay_to_name, cp.legal_name ||
        coalesce(&#39;:&#39; || ec.description,&#39;&#39;)) as name,
        e.entity_class, ec.discount_account_id, ec.meta_number
 FROM entity_credit_account ec
 JOIN entity e ON (ec.entity_id = e.id)
 JOIN company cp ON (cp.entity_id = e.id)
 WHERE ec.id = $1;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_entity_accounts(in_account_class integer, in_vc_name text, in_vc_idn text, in_datefrom date, in_dateto date) -->
    <section id="public.function.payment-get-entity-accounts-in-account-class-integer-in-vc-name-text-in-vc-idn-text-in-datefrom-date-in-dateto-date"
             xreflabel="()">
      <title id="public.function.payment-get-entity-accounts-in-account-class-integer-in-vc-name-text-in-vc-idn-text-in-datefrom-date-in-dateto-date-title">
       payment_get_entity_accounts(in_account_class integer, in_vc_name text, in_vc_idn text, in_datefrom date, in_dateto date)
      </title>
      <titleabbrev id="public.function.payment-get-entity-accounts-in-account-class-integer-in-vc-name-text-in-vc-idn-text-in-datefrom-date-in-dateto-date-titleabbrev">
       payment_get_entity_accounts(in_account_class integer, in_vc_name text, in_vc_idn text, in_datefrom date, in_dateto date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_vc_info</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a minimal set of information about customer or vendor accounts
as needed for discount calculations and the like.
        <programlisting>
              SELECT ec.id, coalesce(ec.pay_to_name, e.name ||
                     coalesce(&#39;:&#39; || ec.description,&#39;&#39;)) as name,
                     e.entity_class, ec.discount_account_id, ec.meta_number
                FROM entity_credit_account ec
                JOIN entity e ON (ec.entity_id = e.id)
                WHERE ec.entity_class = in_account_class
                AND (e.name ilike coalesce(&#39;%&#39;||in_vc_name||&#39;%&#39;,&#39;%%&#39;)
                    OR EXISTS (select 1 FROM company
                                WHERE entity_id = e.id AND tax_id = in_vc_idn))
                AND (coalesce(ec.enddate, now()::date)
                     &gt;= coalesce(in_datefrom, now()::date))
                AND (coalesce(ec.startdate, now()::date)
                     &lt;= coalesce(in_dateto, now()::date))
 </programlisting>
      </para>
    </section>

<!-- Function payment_get_open_accounts(in_account_class integer, in_datefrom date, in_dateto date) -->
    <section id="public.function.payment-get-open-accounts-in-account-class-integer-in-datefrom-date-in-dateto-date"
             xreflabel="()">
      <title id="public.function.payment-get-open-accounts-in-account-class-integer-in-datefrom-date-in-dateto-date-title">
       payment_get_open_accounts(in_account_class integer, in_datefrom date, in_dateto date)
      </title>
      <titleabbrev id="public.function.payment-get-open-accounts-in-account-class-integer-in-datefrom-date-in-dateto-date-titleabbrev">
       payment_get_open_accounts(in_account_class integer, in_datefrom date, in_dateto date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_open_account</seg>
        </seglistitem>
       </segmentedlist>
 
        This function takes a single argument (1 for vendor, 2 for customer as
always) and returns all entities with open accounts of the appropriate type. 
        <programlisting>
                SELECT ec.id, e.name, ec.entity_class
                FROM entity e
                JOIN entity_credit_account ec ON (ec.entity_id = e.id)
                        WHERE ec.entity_class = in_account_class
                        AND (coalesce(ec.enddate, now()::date)
                             &lt;= coalesce(in_dateto, now()::date))
                        AND (coalesce(ec.startdate, now()::date)
                             &gt;= coalesce(in_datefrom, now()::date))
                        AND CASE WHEN in_account_class = 1 THEN
                                ec.id IN
                                (SELECT entity_credit_account
                                   FROM acc_trans
                                   JOIN chart ON (acc_trans.chart_id = chart.id)
                                   JOIN ap ON (acc_trans.trans_id = ap.id)
                                   WHERE link = &#39;AP&#39;
                                   GROUP BY chart_id,
                                         trans_id, entity_credit_account
                                   HAVING SUM(acc_trans.amount) &lt;&gt; 0)
                               WHEN in_account_class = 2 THEN
                                ec.id IN (SELECT entity_credit_account
                                   FROM acc_trans
                                   JOIN chart ON (acc_trans.chart_id = chart.id)
                                   JOIN ar ON (acc_trans.trans_id = ar.id)
                                   WHERE link = &#39;AR&#39;
                                   GROUP BY chart_id,
                                         trans_id, entity_credit_account
                                   HAVING SUM(acc_trans.amount) &lt;&gt; 0)
                          END;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_open_invoice(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric, in_invnumber text) -->
    <section id="public.function.payment-get-open-invoice-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric-in-invnumber-text"
             xreflabel="()">
      <title id="public.function.payment-get-open-invoice-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric-in-invnumber-text-title">
       payment_get_open_invoice(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric, in_invnumber text)
      </title>
      <titleabbrev id="public.function.payment-get-open-invoice-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric-in-invnumber-text-titleabbrev">
       payment_get_open_invoice(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric, in_invnumber text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_invoice</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function is based on payment_get_open_invoices and returns only one invoice if the in_invnumber is set.
if no in_invnumber is passed this function behaves the same as payment_get_open_invoices

        <programlisting>
                SELECT * from payment_get_open_invoices(in_account_class, in_entity_credit_id, in_curr, in_datefrom, in_dateto, in_amountfrom,
                in_amountto)
                WHERE (invnumber like in_invnumber OR in_invnumber IS NULL);

</programlisting>
      </para>
    </section>

<!-- Function payment_get_open_invoices(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric) -->
    <section id="public.function.payment-get-open-invoices-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric"
             xreflabel="()">
      <title id="public.function.payment-get-open-invoices-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric-title">
       payment_get_open_invoices(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric)
      </title>
      <titleabbrev id="public.function.payment-get-open-invoices-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-datefrom-date-in-dateto-date-in-amountfrom-numeric-in-amountto-numeric-titleabbrev">
       payment_get_open_invoices(in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_datefrom date, in_dateto date, in_amountfrom numeric, in_amountto numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_invoice</seg>
        </seglistitem>
       </segmentedlist>
 
        This function is the base for get_open_invoice and returns all open invoices for the entity_credit_id
it has a lot of options to enable filtering and use the same logic for entity_class_id and currency. 
        <programlisting>
                SELECT a.id AS invoice_id, a.invnumber AS invnumber,a.invoice AS invoice,
                       a.transdate AS invoice_date, a.amount AS amount,
                       a.amount/
                       (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
                         THEN 1
                        ELSE
                        (CASE WHEN in_account_class = 2
                              THEN ex.buy
                              ELSE ex.sell END)
                        END) as amount_fx,
                       (CASE WHEN c.discount_terms &lt; extract(&#39;days&#39; FROM age(a.transdate))
                        THEN 0
                        ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
                        END) AS discount,
                        (CASE WHEN c.discount_terms &lt; extract(&#39;days&#39; FROM age(a.transdate))
                        THEN 0
                        ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
                        END)/
                        (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
                         THEN 1
                        ELSE
                        (CASE WHEN in_account_class = 2
                              THEN ex.buy
                              ELSE ex.sell END)
                        END) as discount_fx,
                        ac.due - (CASE WHEN c.discount_terms &lt; extract(&#39;days&#39; FROM age(a.transdate))
                        THEN 0
                        ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
                        END) AS due,
                        (ac.due - (CASE WHEN c.discount_terms &lt; extract(&#39;days&#39; FROM age(a.transdate))
                        THEN 0
                        ELSE (coalesce(ac.due, a.amount)) * coalesce(c.discount, 0) / 100
                        END))/
                        (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
                         THEN 1
                         ELSE
                         (CASE WHEN in_account_class = 2
                              THEN ex.buy
                              ELSE ex.sell END)
                         END) AS due_fx,
                        (CASE WHEN a.curr = (SELECT * from defaults_get_defaultcurrency())
                         THEN 1
                         ELSE
                        (CASE WHEN in_account_class = 2
                         THEN ex.buy
                         ELSE ex.sell END)
                         END) AS exchangerate
                 --TODO HV prepare drop entity_id from ap,ar
                 --FROM  (SELECT id, invnumber, transdate, amount, entity_id,
                 FROM  (SELECT id, invnumber, invoice, transdate, amount,
                               1 as invoice_class, curr,
                               entity_credit_account, approved
                          FROM ap
                         UNION
                         --SELECT id, invnumber, transdate, amount, entity_id,
                         SELECT id, invnumber, invoice, transdate, amount,
                               2 AS invoice_class, curr,
                               entity_credit_account, approved
                         FROM ar
                         ) a
                JOIN (SELECT trans_id, chart_id, sum(CASE WHEN in_account_class = 1 THEN amount
                                                  WHEN in_account_class = 2
                                             THEN amount * -1
                                             END) as due
                        FROM acc_trans
                        GROUP BY trans_id, chart_id) ac ON (ac.trans_id = a.id)
                        JOIN chart ON (chart.id = ac.chart_id)
                        LEFT JOIN exchangerate ex ON ( ex.transdate = a.transdate AND ex.curr = a.curr )
                        JOIN entity_credit_account c ON (c.id = a.entity_credit_account)
                --        OR (a.entity_credit_account IS NULL and a.entity_id = c.entity_id))
                        WHERE ((chart.link = &#39;AP&#39; AND in_account_class = 1)
                              OR (chart.link = &#39;AR&#39; AND in_account_class = 2))
                        AND a.invoice_class = in_account_class
                        AND c.entity_class = in_account_class
                        AND c.id = in_entity_credit_id
                        --### short term: ignore fractional cent differences
                        AND a.curr = in_curr
                        AND (a.transdate &gt;= in_datefrom
                             OR in_datefrom IS NULL)
                        AND (a.transdate &lt;= in_dateto
                             OR in_dateto IS NULL)
                        AND (a.amount &gt;= in_amountfrom
                             OR in_amountfrom IS NULL)
                        AND (a.amount &lt;= in_amountto
                             OR in_amountto IS NULL)
                        AND due &lt;&gt; 0
                        AND a.approved = true
                        GROUP BY a.invnumber, a.transdate, a.amount, amount_fx, discount, discount_fx, ac.due, a.id, c.discount_terms, ex.buy, ex.sell, a.curr, a.invoice;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_open_overpayment_entities(in_account_class integer) -->
    <section id="public.function.payment-get-open-overpayment-entities-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.payment-get-open-overpayment-entities-in-account-class-integer-title">
       payment_get_open_overpayment_entities(in_account_class integer)
      </title>
      <titleabbrev id="public.function.payment-get-open-overpayment-entities-in-account-class-integer-titleabbrev">
       payment_get_open_overpayment_entities(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_vc_info</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
                SELECT DISTINCT entity_credit_id, legal_name, e.entity_class, null::int, o.meta_number
                FROM overpayments o
                JOIN entity e ON (e.id=o.entity_id)
                WHERE available &lt;&gt; 0 AND in_account_class = payment_class;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_unused_overpayment(in_account_class integer, in_entity_credit_id integer, in_chart_id integer) -->
    <section id="public.function.payment-get-unused-overpayment-in-account-class-integer-in-entity-credit-id-integer-in-chart-id-integer"
             xreflabel="()">
      <title id="public.function.payment-get-unused-overpayment-in-account-class-integer-in-entity-credit-id-integer-in-chart-id-integer-title">
       payment_get_unused_overpayment(in_account_class integer, in_entity_credit_id integer, in_chart_id integer)
      </title>
      <titleabbrev id="public.function.payment-get-unused-overpayment-in-account-class-integer-in-entity-credit-id-integer-in-chart-id-integer-titleabbrev">
       payment_get_unused_overpayment(in_account_class integer, in_entity_credit_id integer, in_chart_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF overpayments</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of available overpayments
        <programlisting>
              SELECT DISTINCT *
              FROM overpayments
              WHERE payment_class  = in_account_class
              AND entity_credit_id = in_entity_credit_id
              AND available &lt;&gt; 0
              AND (in_chart_id IS NULL OR chart_id = in_chart_id )
              ORDER BY payment_date;
</programlisting>
      </para>
    </section>

<!-- Function payment_get_vc_info(in_entity_credit_id integer, in_location_class_id integer) -->
    <section id="public.function.payment-get-vc-info-in-entity-credit-id-integer-in-location-class-id-integer"
             xreflabel="()">
      <title id="public.function.payment-get-vc-info-in-entity-credit-id-integer-in-location-class-id-integer-title">
       payment_get_vc_info(in_entity_credit_id integer, in_location_class_id integer)
      </title>
      <titleabbrev id="public.function.payment-get-vc-info-in-entity-credit-id-integer-in-location-class-id-integer-titleabbrev">
       payment_get_vc_info(in_entity_credit_id integer, in_location_class_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_location_result</seg>
        </seglistitem>
       </segmentedlist>
 
        This function returns vendor or customer info 
        <programlisting>
                SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
                       l.state, l.mail_code, c.name, lc.class
                FROM location l
                JOIN entity_to_location ctl ON (ctl.location_id = l.id)
                JOIN entity cp ON (ctl.entity_id = cp.id)
                JOIN location_class lc ON (ctl.location_class = lc.id)
                JOIN country c ON (c.id = l.country_id)
                JOIN entity_credit_account ec ON (ec.entity_id = cp.id)
                WHERE ec.id = in_entity_credit_id AND
                      lc.id = in_location_class_id
                ORDER BY lc.id, l.id, c.name
</programlisting>
      </para>
    </section>

<!-- Function payment_post(in_datepaid date, in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_notes text, in_gl_description text, in_cash_account_id integer[], in_amount numeric[], in_cash_approved boolean[], in_source text[], in_memo text[], in_transaction_id integer[], in_op_amount numeric[], in_op_cash_account_id integer[], in_op_source text[], in_op_memo text[], in_op_account_id integer[], in_ovp_payment_id integer[], in_approved boolean) -->
    <section id="public.function.payment-post-in-datepaid-date-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-notes-text-in-gl-description-text-in-cash-account-id-integerARRAY-in-amount-numericARRAY-in-cash-approved-booleanARRAY-in-source-textARRAY-in-memo-textARRAY-in-transaction-id-integerARRAY-in-op-amount-numericARRAY-in-op-cash-account-id-integerARRAY-in-op-source-textARRAY-in-op-memo-textARRAY-in-op-account-id-integerARRAY-in-ovp-payment-id-integerARRAY-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.payment-post-in-datepaid-date-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-notes-text-in-gl-description-text-in-cash-account-id-integerARRAY-in-amount-numericARRAY-in-cash-approved-booleanARRAY-in-source-textARRAY-in-memo-textARRAY-in-transaction-id-integerARRAY-in-op-amount-numericARRAY-in-op-cash-account-id-integerARRAY-in-op-source-textARRAY-in-op-memo-textARRAY-in-op-account-id-integerARRAY-in-ovp-payment-id-integerARRAY-in-approved-boolean-title">
       payment_post(in_datepaid date, in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_notes text, in_gl_description text, in_cash_account_id integer[], in_amount numeric[], in_cash_approved boolean[], in_source text[], in_memo text[], in_transaction_id integer[], in_op_amount numeric[], in_op_cash_account_id integer[], in_op_source text[], in_op_memo text[], in_op_account_id integer[], in_ovp_payment_id integer[], in_approved boolean)
      </title>
      <titleabbrev id="public.function.payment-post-in-datepaid-date-in-account-class-integer-in-entity-credit-id-integer-in-curr-bpchar-in-notes-text-in-gl-description-text-in-cash-account-id-integerARRAY-in-amount-numericARRAY-in-cash-approved-booleanARRAY-in-source-textARRAY-in-memo-textARRAY-in-transaction-id-integerARRAY-in-op-amount-numericARRAY-in-op-cash-account-id-integerARRAY-in-op-source-textARRAY-in-op-memo-textARRAY-in-op-account-id-integerARRAY-in-ovp-payment-id-integerARRAY-in-approved-boolean-titleabbrev">
       payment_post(in_datepaid date, in_account_class integer, in_entity_credit_id integer, in_curr bpchar, in_notes text, in_gl_description text, in_cash_account_id integer[], in_amount numeric[], in_cash_approved boolean[], in_source text[], in_memo text[], in_transaction_id integer[], in_op_amount numeric[], in_op_cash_account_id integer[], in_op_source text[], in_op_memo text[], in_op_account_id integer[], in_ovp_payment_id integer[], in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Posts a payment.  in_op_* arrays are cross-indexed with eachother.
Other arrays are cross-indexed with eachother.

This API will probably change in 1.4 as we start looking at using more custom
complex types and arrays of those (requires Pg 8.4 or higher).

        <programlisting>
DECLARE var_payment_id int;
DECLARE var_gl_id int;
DECLARE var_entry record;
DECLARE var_entry_id int[];
DECLARE out_count int;
DECLARE coa_id record;
DECLARE var_employee int;
DECLARE var_account_id int;
DECLARE default_currency char(3);
DECLARE current_exchangerate numeric;
DECLARE old_exchangerate numeric;
DECLARE fx_gain_loss_amount numeric;
BEGIN
      IF array_upper(in_amount, 1) &lt;&gt; array_upper(in_cash_account_id, 1) THEN
          RAISE EXCEPTION &#39;Wrong number of accounts&#39;;
      END IF;

        SELECT * INTO default_currency  FROM defaults_get_defaultcurrency();
        SELECT * INTO current_exchangerate FROM currency_get_exchangerate(in_curr, in_datepaid, in_account_class);


        SELECT INTO var_employee p.id
        FROM users u
        JOIN person p ON (u.entity_id=p.entity_id)
        WHERE username = SESSION_USER LIMIT 1;
        --
        -- WE HAVE TO INSERT THE PAYMENT, USING THE GL INFORMATION
        -- THE ID IS GENERATED BY payment_id_seq
        --
        INSERT INTO payment (reference, payment_class, payment_date,
                              employee_id, currency, notes, entity_credit_id)
        VALUES ((CASE WHEN in_account_class = 1 THEN
                                        setting_increment(&#39;rcptnumber&#39;) -- I FOUND THIS ON sql/modules/Settings.sql
                                     ELSE                                               -- and it is very usefull
                                        setting_increment(&#39;paynumber&#39;)
                                     END),
                 in_account_class, in_datepaid, var_employee,
                 in_curr, in_notes, in_entity_credit_id);
        SELECT currval(&#39;payment_id_seq&#39;) INTO var_payment_id; -- WE&#39;LL NEED THIS VALUE TO USE payment_link table
        -- WE&#39;LL NEED THIS VALUE TO JOIN WITH PAYMENT
        -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
        --
        -- FIRST WE SHOULD INSERT THE CASH ACCOUNTS
        --
        -- WE SHOULD HAVE THE DATA STORED AS (ACCNO, AMOUNT), SO
     IF (array_upper(in_cash_account_id, 1) &gt; 0) THEN
        FOR out_count IN
                        array_lower(in_cash_account_id, 1) ..
                        array_upper(in_cash_account_id, 1)
        LOOP
                INSERT INTO acc_trans (chart_id, amount,
                                       trans_id, transdate, approved, source, memo)
                VALUES (in_cash_account_id[out_count],
                        CASE WHEN in_account_class = 1 THEN in_amount[out_count]
                        ELSE in_amount[out_count]* - 1
                        END,
                        in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
                        in_source[out_count], in_memo[out_count]);
                INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
                IF (in_ovp_payment_id IS NOT NULL
                    AND in_ovp_payment_id[out_count] IS NOT NULL) THEN
                   INSERT INTO payment_links
                   VALUES (in_ovp_payment_id[out_count],
                           currval(&#39;acc_trans_entry_id_seq&#39;), 0);
                END IF;


                IF current_exchangerate &lt;&gt; 1 THEN
                   INSERT INTO acc_trans (chart_id, amount, fx_transaction,
                                              trans_id, transdate, approved, source, memo)
                    VALUES (in_cash_account_id[out_count],
                        CASE WHEN in_account_class = 1 THEN in_amount[out_count]*(current_exchangerate-1)
                        ELSE in_amount[out_count]*(current_exchangerate-1)* - 1
                        END, &#39;t&#39;::boolean,
                        in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
                        in_source[out_count], in_memo[out_count]);
                   INSERT INTO payment_links
                   VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
                   IF (in_ovp_payment_id IS NOT NULL
                       AND in_ovp_payment_id[out_count] IS NOT NULL) THEN
                      INSERT INTO payment_links
                      VALUES (in_ovp_payment_id[out_count],
                              currval(&#39;acc_trans_entry_id_seq&#39;), 0);
                   END IF;
                END IF;


        END LOOP;
        -- NOW LETS HANDLE THE AR/AP ACCOUNTS
        -- WE RECEIVED THE TRANSACTIONS_ID AND WE CAN OBTAIN THE ACCOUNT FROM THERE
        FOR out_count IN
                     array_lower(in_transaction_id, 1) ..
                     array_upper(in_transaction_id, 1)
       LOOP
               SELECT INTO var_account_id chart_id FROM acc_trans as ac
                JOIN chart as c ON (c.id = ac.chart_id)
                WHERE
                trans_id = in_transaction_id[out_count] AND
                ( c.link = &#39;AP&#39; OR c.link = &#39;AR&#39; );
        -- We need to know the exchangerate of this transaction
        -- ### BUG: we don&#39;t have a guarantee that the transaction is
        --          the same currency as in_curr, so, we can&#39;t use
        --          current_exchangerate as the basis for fx gain/loss
        --          calculations
        IF (in_curr = default_currency) THEN
           old_exchangerate := 1;
        ELSIF (in_account_class = 2) THEN
           SELECT buy INTO old_exchangerate
           FROM exchangerate e
           JOIN ar a ON (a.transdate = e.transdate)
                        AND (a.curr = e.curr)
           WHERE a.id = in_transaction_id[out_count];
        ELSE
           SELECT sell INTO old_exchangerate
           FROM exchangerate e
           JOIN ap a ON (a.transdate = e.transdate)
                        AND (a.curr = e.curr)
           WHERE a.id = in_transaction_id[out_count];
        END IF;
        -- Now we post the AP/AR transaction
        INSERT INTO acc_trans (chart_id, amount,
                                trans_id, transdate, approved, source, memo)
                VALUES (var_account_id,
                        CASE WHEN in_account_class = 1 THEN
                        in_amount[out_count]* -1
                        ELSE in_amount[out_count]
                        END,
                        in_transaction_id[out_count], in_datepaid,  coalesce(in_approved, true),
                        in_source[out_count], in_memo[out_count]);
         -- Now we set the links
         INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
         INSERT INTO acc_trans (chart_id, amount, fx_transaction,
                                trans_id, transdate, approved, source, memo)
                VALUES (var_account_id,
                        CASE WHEN in_account_class = 1 THEN
                        in_amount[out_count]*(old_exchangerate-1) * -1
                        ELSE in_amount[out_count]*(old_exchangerate-1)
                        END, &#39;t&#39;::boolean,
                        in_transaction_id[out_count], in_datepaid,  coalesce(in_approved, true),
                        in_source[out_count], in_memo[out_count]);
         -- Now we set the links
         INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
         -- Lets set the gain/loss, if  fx_gain_loss_amount equals zero then we dont need to post
        -- any transaction
       fx_gain_loss_amount := in_amount[out_count]*current_exchangerate - in_amount[out_count]*old_exchangerate;
       IF (in_account_class = 1) THEN
         -- in case of vendor invoices, the invoice amounts have been negated, do the same with the diff
         fx_gain_loss_amount := fx_gain_loss_amount * -1;
       END IF;

       IF (fx_gain_loss_amount &lt; 0) THEN
            INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
            VALUES ((select value::int from defaults WHERE setting_key = &#39;fxgain_accno_id&#39;),
                    fx_gain_loss_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
                    in_source[out_count]);
            -- Now we set the links
            INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
         ELSIF (fx_gain_loss_amount &gt; 0) THEN
            INSERT INTO acc_trans (chart_id, amount, trans_id, transdate, approved, source)
            VALUES ((select value::int from defaults WHERE setting_key = &#39;fxloss_accno_id&#39;),
                    fx_gain_loss_amount, in_transaction_id[out_count], in_datepaid, coalesce(in_approved, true),
                    in_source[out_count]);
            -- Now we set the links
            INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 1);
         END IF;
       END LOOP;
     END IF; -- END IF
--
-- WE NEED TO HANDLE THE OVERPAYMENTS NOW
--
       --
       -- FIRST WE HAVE TO MAKE THE GL TO HOLD THE OVERPAYMENT TRANSACTIONS
       -- THE ID IS GENERATED BY gl_id_seq
       --

  IF (array_upper(in_op_cash_account_id, 1) &gt; 0) THEN
       INSERT INTO gl (reference, description, transdate,
                       person_id, notes, approved)
              VALUES (setting_increment(&#39;glnumber&#39;),
                      in_gl_description, in_datepaid, var_employee,
                      in_notes, in_approved);
       SELECT currval(&#39;id&#39;) INTO var_gl_id;
--
-- WE NEED TO SET THE GL_ID FIELD ON PAYMENT&#39;S TABLE
--
       UPDATE payment SET gl_id = var_gl_id
       WHERE id = var_payment_id;
       -- NOW COMES THE HEAVY PART, STORING ALL THE POSSIBLE TRANSACTIONS...
       --
       -- FIRST WE SHOULD INSERT THE OVERPAYMENT CASH ACCOUNTS
       --
        FOR out_count IN
                        array_lower(in_op_cash_account_id, 1) ..
                        array_upper(in_op_cash_account_id, 1)
        LOOP
                INSERT INTO acc_trans (chart_id, amount,
                                       trans_id, transdate, approved, source, memo)
                VALUES (in_op_cash_account_id[out_count],
                        CASE WHEN in_account_class = 1 THEN in_op_amount[out_count]
                        ELSE in_op_amount[out_count] * - 1
                        END,
                        var_gl_id, in_datepaid, coalesce(in_approved, true),
                        in_op_source[out_count], in_op_memo[out_count]);
                INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 2);

        END LOOP;
        -- NOW LETS HANDLE THE OVERPAYMENT ACCOUNTS
        FOR out_count IN
                     array_lower(in_op_account_id, 1) ..
                     array_upper(in_op_account_id, 1)
        LOOP
         INSERT INTO acc_trans (chart_id, amount,
                                trans_id, transdate, approved, source, memo)
                VALUES (in_op_account_id[out_count],
                        CASE WHEN in_account_class = 1 THEN in_op_amount[out_count] * -1
                        ELSE in_op_amount[out_count]
                        END,
                        var_gl_id, in_datepaid,  coalesce(in_approved, true),
                        in_op_source[out_count], in_op_memo[out_count]);
                INSERT INTO payment_links
                VALUES (var_payment_id, currval(&#39;acc_trans_entry_id_seq&#39;), 2);
        END LOOP;
 END IF;
 return var_payment_id;
END;
</programlisting>
      </para>
    </section>

<!-- Function payment_type__get_label(in_payment_type_id integer) -->
    <section id="public.function.payment-type-get-label-in-payment-type-id-integer"
             xreflabel="()">
      <title id="public.function.payment-type-get-label-in-payment-type-id-integer-title">
       payment_type__get_label(in_payment_type_id integer)
      </title>
      <titleabbrev id="public.function.payment-type-get-label-in-payment-type-id-integer-titleabbrev">
       payment_type__get_label(in_payment_type_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_type</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns all information on a payment type by the id.  This should be renamed
to account for its behavior in future versions.
        <programlisting>
SELECT * FROM payment_type where id=in_payment_type_id;
</programlisting>
      </para>
    </section>

<!-- Function payment_type__list() -->
    <section id="public.function.payment-type-list"
             xreflabel="()">
      <title id="public.function.payment-type-list-title">
       payment_type__list()
      </title>
      <titleabbrev id="public.function.payment-type-list-titleabbrev">
       payment_type__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payment_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payment_type;
</programlisting>
      </para>
    </section>

<!-- Function payments_get_open_currencies(in_account_class integer) -->
    <section id="public.function.payments-get-open-currencies-in-account-class-integer"
             xreflabel="()">
      <title id="public.function.payments-get-open-currencies-in-account-class-integer-title">
       payments_get_open_currencies(in_account_class integer)
      </title>
      <titleabbrev id="public.function.payments-get-open-currencies-in-account-class-integer-titleabbrev">
       payments_get_open_currencies(in_account_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF bpchar</seg>
        </seglistitem>
       </segmentedlist>
 
        This does a sparse scan to find currencies attached to open invoices.

It should scale per the number of currencies used rather than the size of the
ar or ap tables.

        <programlisting>
DECLARE result char(3);
BEGIN
select min(curr) into result from ar WHERE in_account_class = 2
union
select min(curr) from ap WHERE in_account_class = 1;


LOOP
   EXIT WHEN result IS NULL;
   return next result;

   SELECT min(curr) INTO result from ar
    where in_account_class = 2 and curr &gt; result
            union
   select min(curr) from ap
    WHERE in_account_class = 1 and curr &gt; result
    LIMIT 1;

END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function payments_set_exchangerate(in_account_class integer, in_exchangerate numeric, in_curr bpchar, in_datepaid date) -->
    <section id="public.function.payments-set-exchangerate-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar-in-datepaid-date"
             xreflabel="()">
      <title id="public.function.payments-set-exchangerate-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar-in-datepaid-date-title">
       payments_set_exchangerate(in_account_class integer, in_exchangerate numeric, in_curr bpchar, in_datepaid date)
      </title>
      <titleabbrev id="public.function.payments-set-exchangerate-in-account-class-integer-in-exchangerate-numeric-in-curr-bpchar-in-datepaid-date-titleabbrev">
       payments_set_exchangerate(in_account_class integer, in_exchangerate numeric, in_curr bpchar, in_datepaid date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        1.3 only.  This will be replaced by a more generic function in 1.4.

This sets the exchange rate for a class of transactions (payable, receivable)
to a certain rate for a specific date.
        <programlisting>
DECLARE current_exrate  exchangerate%ROWTYPE;
BEGIN
select  * INTO current_exrate
        FROM  exchangerate
        WHERE transdate = in_datepaid
              AND curr = in_curr;
IF current_exrate.transdate = in_datepaid THEN
   IF in_account_class = 2 THEN
      UPDATE exchangerate set buy = in_exchangerate  where transdate = in_datepaid;
   ELSE
      UPDATE exchangerate set sell = in_exchangerate where transdate = in_datepaid;
   END IF;
   RETURN 0;
ELSE
    IF in_account_class = 2 THEN
     INSERT INTO exchangerate (curr, transdate, buy) values (in_curr, in_datepaid, in_exchangerate);
  ELSE
     INSERT INTO exchangerate (curr, transdate, sell) values (in_curr, in_datepaid, in_exchangerate);
  END IF;
RETURN 0;
END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function payroll_deduction_type__search(in_account_id integer, in_pdc_id integer, in_country_id integer, in_label text, in_unit text) -->
    <section id="public.function.payroll-deduction-type-search-in-account-id-integer-in-pdc-id-integer-in-country-id-integer-in-label-text-in-unit-text"
             xreflabel="()">
      <title id="public.function.payroll-deduction-type-search-in-account-id-integer-in-pdc-id-integer-in-country-id-integer-in-label-text-in-unit-text-title">
       payroll_deduction_type__search(in_account_id integer, in_pdc_id integer, in_country_id integer, in_label text, in_unit text)
      </title>
      <titleabbrev id="public.function.payroll-deduction-type-search-in-account-id-integer-in-pdc-id-integer-in-country-id-integer-in-label-text-in-unit-text-titleabbrev">
       payroll_deduction_type__search(in_account_id integer, in_pdc_id integer, in_country_id integer, in_label text, in_unit text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_deduction_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT *
  FROM payroll_deduction_type
 where (account_id = $1 OR $1 IS NULL) AND
       (pdc_id = $2 OR $2 IS NULL) AND
       (country_id = $3 OR $3 IS NULL) AND
       ($4 IS NULL OR label LIKE $4 || &#39;%&#39;) AND
       (unit = $5 or $5 IS NULL);
</programlisting>
      </para>
    </section>

<!-- Function payroll_income_category__list() -->
    <section id="public.function.payroll-income-category-list"
             xreflabel="()">
      <title id="public.function.payroll-income-category-list-title">
       payroll_income_category__list()
      </title>
      <titleabbrev id="public.function.payroll-income-category-list-titleabbrev">
       payroll_income_category__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_income_category</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_income_category order by id;
</programlisting>
      </para>
    </section>

<!-- Function payroll_income_class__for_country(in_country_id integer) -->
    <section id="public.function.payroll-income-class-for-country-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.payroll-income-class-for-country-in-country-id-integer-title">
       payroll_income_class__for_country(in_country_id integer)
      </title>
      <titleabbrev id="public.function.payroll-income-class-for-country-in-country-id-integer-titleabbrev">
       payroll_income_class__for_country(in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_income_class</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_income_class where country_id = $1
ORDER BY label;
</programlisting>
      </para>
    </section>

<!-- Function payroll_income_type__get(in_id integer) -->
    <section id="public.function.payroll-income-type-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.payroll-income-type-get-in-id-integer-title">
       payroll_income_type__get(in_id integer)
      </title>
      <titleabbrev id="public.function.payroll-income-type-get-in-id-integer-titleabbrev">
       payroll_income_type__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>payroll_income_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_income_type WHERE id  = $1;
</programlisting>
      </para>
    </section>

<!-- Function payroll_income_type__save(in_id integer, in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text, in_default_amount numeric) -->
    <section id="public.function.payroll-income-type-save-in-id-integer-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text-in-default-amount-numeric"
             xreflabel="()">
      <title id="public.function.payroll-income-type-save-in-id-integer-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text-in-default-amount-numeric-title">
       payroll_income_type__save(in_id integer, in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text, in_default_amount numeric)
      </title>
      <titleabbrev id="public.function.payroll-income-type-save-in-id-integer-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text-in-default-amount-numeric-titleabbrev">
       payroll_income_type__save(in_id integer, in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text, in_default_amount numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>payroll_income_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

   DECLARE retval payroll_income_type;

BEGIN
   UPDATE payroll_income_type
      SET account_id = in_account_id,
          pic_id = in_pic_id,
          country_id = in_country_id,
          label = in_label,
          unit = in_unit,
          default_amount = in_default_amount
    WHERE id = in_id;

   IF FOUND THEN
       retval := payroll_income_type__get(in_id);
       RETURN retval;
   END IF;

   INSERT INTO payroll_income_type
          (account_id, pic_id, country_id, label, unit, default_amount)
   VALUES (in_account_id, in_pic_id, in_country_id, in_label, in_unit,
           in_default_amount);

   retval := payroll_income_type__get(currval(&#39;payroll_income_type_id_seq&#39;)::int);
   RETURN retval;

END;
</programlisting>
      </para>
    </section>

<!-- Function payroll_income_type__search(in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text) -->
    <section id="public.function.payroll-income-type-search-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text"
             xreflabel="()">
      <title id="public.function.payroll-income-type-search-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text-title">
       payroll_income_type__search(in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text)
      </title>
      <titleabbrev id="public.function.payroll-income-type-search-in-account-id-integer-in-pic-id-integer-in-country-id-integer-in-label-text-in-unit-text-titleabbrev">
       payroll_income_type__search(in_account_id integer, in_pic_id integer, in_country_id integer, in_label text, in_unit text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_income_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT *
  FROM payroll_income_type
 where (account_id = $1 OR $1 IS NULL) AND
       (pic_id = $2 OR $2 IS NULL) AND
       (country_id = $3 OR $3 IS NULL) AND
       ($4 IS NULL OR label LIKE $4 || &#39;%&#39;) AND
       (unit = $5 or $5 IS NULL);
</programlisting>
      </para>
    </section>

<!-- Function periods_get() -->
    <section id="public.function.periods-get"
             xreflabel="()">
      <title id="public.function.periods-get-title">
       periods_get()
      </title>
      <titleabbrev id="public.function.periods-get-titleabbrev">
       periods_get()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF periods</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns dates for year to date, and last year.
        <programlisting>
SELECT * FROM periods ORDER BY id
</programlisting>
      </para>
    </section>

<!-- Function person__delete_contact(in_person_id integer, in_contact_class_id integer, in_contact text) -->
    <section id="public.function.person-delete-contact-in-person-id-integer-in-contact-class-id-integer-in-contact-text"
             xreflabel="()">
      <title id="public.function.person-delete-contact-in-person-id-integer-in-contact-class-id-integer-in-contact-text-title">
       person__delete_contact(in_person_id integer, in_contact_class_id integer, in_contact text)
      </title>
      <titleabbrev id="public.function.person-delete-contact-in-person-id-integer-in-contact-class-id-integer-in-contact-text-titleabbrev">
       person__delete_contact(in_person_id integer, in_contact_class_id integer, in_contact text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes a contact record specified for the person.  Returns true if a record
was found and deleted, false if not.
        <programlisting>
DELETE FROM entity_to_contact
 WHERE entity_id = (SELECT entity_id FROM person WHERE id = in_person_id)
       and contact_class_id = in_contact_class_id
       and contact= in_contact
RETURNING TRUE;
</programlisting>
      </para>
    </section>

<!-- Function person__delete_location(in_person_id integer, in_location_id integer, in_location_class integer) -->
    <section id="public.function.person-delete-location-in-person-id-integer-in-location-id-integer-in-location-class-integer"
             xreflabel="()">
      <title id="public.function.person-delete-location-in-person-id-integer-in-location-id-integer-in-location-class-integer-title">
       person__delete_location(in_person_id integer, in_location_id integer, in_location_class integer)
      </title>
      <titleabbrev id="public.function.person-delete-location-in-person-id-integer-in-location-id-integer-in-location-class-integer-titleabbrev">
       person__delete_location(in_person_id integer, in_location_id integer, in_location_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Deletes a location mapping to a person.  Returns true if found, false if no
data deleted.
        <programlisting>

DELETE FROM entity_to_location
 WHERE entity_id = (select entity_id from person where id = in_person_id)
       AND location_id = in_location_id
       AND location_class = in_location_class
RETURNING TRUE;

</programlisting>
      </para>
    </section>

<!-- Function person__get(in_entity_id integer) -->
    <section id="public.function.person-get-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.person-get-in-entity-id-integer-title">
       person__get(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.person-get-in-entity-id-integer-titleabbrev">
       person__get(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>person_entity</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT e.id, e.control_code, e.name, e.country_id, c.name,
       p.first_name, p.middle_name, p.last_name, e.entity_class,
       p.birthdate, p.personal_id
  FROM entity e
  JOIN country c ON c.id = e.country_id
  JOIN person p ON p.entity_id = e.id
 WHERE e.id = $1;
</programlisting>
      </para>
    </section>

<!-- Function person__get_by_cc(in_control_code text) -->
    <section id="public.function.person-get-by-cc-in-control-code-text"
             xreflabel="()">
      <title id="public.function.person-get-by-cc-in-control-code-text-title">
       person__get_by_cc(in_control_code text)
      </title>
      <titleabbrev id="public.function.person-get-by-cc-in-control-code-text-titleabbrev">
       person__get_by_cc(in_control_code text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>person_entity</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT e.id, e.control_code, e.name, e.country_id, c.name,
       p.first_name, p.middle_name, p.last_name, e.entity_class,
       p.birthdate, p.personal_id
  FROM entity e
  JOIN country c ON c.id = e.country_id
  JOIN person p ON p.entity_id = e.id
 WHERE e.control_code = $1;
</programlisting>
      </para>
    </section>

<!-- Function person__get_my_entity_id() -->
    <section id="public.function.person-get-my-entity-id"
             xreflabel="()">
      <title id="public.function.person-get-my-entity-id-title">
       person__get_my_entity_id()
      </title>
      <titleabbrev id="public.function.person-get-my-entity-id-titleabbrev">
       person__get_my_entity_id()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the entity_id of the current, logged in user.
        <programlisting>
        SELECT entity_id from users where username = SESSION_USER;
</programlisting>
      </para>
    </section>

<!-- Function person__get_my_id() -->
    <section id="public.function.person-get-my-id"
             xreflabel="()">
      <title id="public.function.person-get-my-id-title">
       person__get_my_id()
      </title>
      <titleabbrev id="public.function.person-get-my-id-titleabbrev">
       person__get_my_id()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the person id of the current, logged in user.
        <programlisting>
        SELECT p.id from person p
        JOIN users u ON u.entity_id = p.entity_id
        WHERE username = SESSION_USER;
</programlisting>
      </para>
    </section>

<!-- Function person__list_bank_account(in_entity_id integer) -->
    <section id="public.function.person-list-bank-account-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.person-list-bank-account-in-entity-id-integer-title">
       person__list_bank_account(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.person-list-bank-account-in-entity-id-integer-titleabbrev">
       person__list_bank_account(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_bank_account</seg>
        </seglistitem>
       </segmentedlist>
 
        Lists bank accounts for a person
        <programlisting>
SELECT * from entity_bank_account where entity_id = in_entity_id
</programlisting>
      </para>
    </section>

<!-- Function person__list_contacts(in_entity_id integer) -->
    <section id="public.function.person-list-contacts-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.person-list-contacts-in-entity-id-integer-title">
       person__list_contacts(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.person-list-contacts-in-entity-id-integer-titleabbrev">
       person__list_contacts(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF contact_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of contacts attached to the function.
        <programlisting>
                SELECT cc.class, cc.id, c.description, c.contact
                FROM entity_to_contact c
                JOIN contact_class cc ON (c.contact_class_id = cc.id)
                JOIN person p ON (c.entity_id = p.entity_id)
                WHERE p.entity_id = in_entity_id
</programlisting>
      </para>
    </section>

<!-- Function person__list_languages() -->
    <section id="public.function.person-list-languages"
             xreflabel="()">
      <title id="public.function.person-list-languages-title">
       person__list_languages()
      </title>
      <titleabbrev id="public.function.person-list-languages-titleabbrev">
       person__list_languages()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF language</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of languages ordered by code
        <programlisting> SELECT * FROM language ORDER BY description ASC </programlisting>
      </para>
    </section>

<!-- Function person__list_locations(in_entity_id integer) -->
    <section id="public.function.person-list-locations-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.person-list-locations-in-entity-id-integer-title">
       person__list_locations(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.person-list-locations-in-entity-id-integer-titleabbrev">
       person__list_locations(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF location_result</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of locations specified attached to the person.
        <programlisting>
DECLARE out_row RECORD;
BEGIN
        FOR out_row IN
                SELECT l.id, l.line_one, l.line_two, l.line_three, l.city,
                        l.state, l.mail_code, c.id, c.name, lc.id, lc.class
                FROM location l
                JOIN entity_to_location ctl ON (ctl.location_id = l.id)
                JOIN person p ON (ctl.entity_id = p.entity_id)
                JOIN location_class lc ON (ctl.location_class = lc.id)
                JOIN country c ON (c.id = l.country_id)
                WHERE p.entity_id = in_entity_id
                ORDER BY lc.id, l.id, c.name
        LOOP
                RETURN NEXT out_row;
        END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function person__list_notes(in_entity_id integer) -->
    <section id="public.function.person-list-notes-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.person-list-notes-in-entity-id-integer-title">
       person__list_notes(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.person-list-notes-in-entity-id-integer-titleabbrev">
       person__list_notes(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of notes attached to a person.
        <programlisting>
                SELECT *
                FROM entity_note
                WHERE ref_key = in_entity_id
                ORDER BY created
</programlisting>
      </para>
    </section>

<!-- Function person__list_salutations() -->
    <section id="public.function.person-list-salutations"
             xreflabel="()">
      <title id="public.function.person-list-salutations-title">
       person__list_salutations()
      </title>
      <titleabbrev id="public.function.person-list-salutations-titleabbrev">
       person__list_salutations()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF salutation</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of salutations ordered by id.
        <programlisting> SELECT * FROM salutation ORDER BY id ASC </programlisting>
      </para>
    </section>

<!-- Function person__save(in_entity_id integer, in_salutation_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer, in_birthdate date, in_personal_id text) -->
    <section id="public.function.person-save-in-entity-id-integer-in-salutation-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer-in-birthdate-date-in-personal-id-text"
             xreflabel="()">
      <title id="public.function.person-save-in-entity-id-integer-in-salutation-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer-in-birthdate-date-in-personal-id-text-title">
       person__save(in_entity_id integer, in_salutation_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer, in_birthdate date, in_personal_id text)
      </title>
      <titleabbrev id="public.function.person-save-in-entity-id-integer-in-salutation-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer-in-birthdate-date-in-personal-id-text-titleabbrev">
       person__save(in_entity_id integer, in_salutation_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer, in_birthdate date, in_personal_id text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves the person with the information specified.  Returns the entity_id
of the record saved.
        <programlisting>

    DECLARE
        e_id int;
        e entity;
        loc location;
        l_id int;
        p_id int;
    BEGIN

    select * into e from entity where id = in_entity_id and entity_class = 3;
    e_id := in_entity_id;

    IF FOUND THEN
        UPDATE entity
           SET name = in_first_name || &#39; &#39; || in_last_name,
               country_id = in_country_id
         WHERE id = in_entity_id;
    ELSE
        INSERT INTO entity (name, entity_class, country_id)
        values (in_first_name || &#39; &#39; || in_last_name, 3, in_country_id);
        e_id := currval(&#39;entity_id_seq&#39;);

    END IF;


    UPDATE person SET
            salutation_id = in_salutation_id,
            first_name = in_first_name,
            last_name = in_last_name,
            middle_name = in_middle_name,
            birthdate = in_birthdate,
            personal_id = in_personal_id
    WHERE
            entity_id = in_entity_id;
    IF FOUND THEN
        RETURN in_entity_id;
    ELSE
        -- Do an insert

        INSERT INTO person (salutation_id, first_name, last_name, entity_id,
                           birthdate, personal_id)
        VALUES (in_salutation_id, in_first_name, in_last_name, e_id,
                in_birthdate, in_personal_id);

        RETURN e_id;

    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function person__save_contact(in_entity_id integer, in_contact_class integer, in_old_contact text, in_contact_new text, in_description text, in_old_contact_class integer) -->
    <section id="public.function.person-save-contact-in-entity-id-integer-in-contact-class-integer-in-old-contact-text-in-contact-new-text-in-description-text-in-old-contact-class-integer"
             xreflabel="()">
      <title id="public.function.person-save-contact-in-entity-id-integer-in-contact-class-integer-in-old-contact-text-in-contact-new-text-in-description-text-in-old-contact-class-integer-title">
       person__save_contact(in_entity_id integer, in_contact_class integer, in_old_contact text, in_contact_new text, in_description text, in_old_contact_class integer)
      </title>
      <titleabbrev id="public.function.person-save-contact-in-entity-id-integer-in-contact-class-integer-in-old-contact-text-in-contact-new-text-in-description-text-in-old-contact-class-integer-titleabbrev">
       person__save_contact(in_entity_id integer, in_contact_class integer, in_old_contact text, in_contact_new text, in_description text, in_old_contact_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves saves contact info.  Returns 1 if a row was inserted, 0 if it was
updated. 
        <programlisting>
DECLARE
    out_id int;
    v_orig entity_to_contact;
BEGIN

    SELECT cc.* into v_orig
      FROM entity_to_contact cc
      JOIN person p ON (p.entity_id = cc.entity_id)
     WHERE p.entity_id = in_entity_id
    and cc.contact_class_id = in_old_contact_class
    AND cc.contact = in_old_contact;

    IF NOT FOUND THEN

        -- create
        INSERT INTO entity_to_contact
               (entity_id, contact_class_id, contact, description)
        VALUES (in_entity_id, in_contact_class, in_contact_new, in_description);

        return 1;
    ELSE
        -- edit.
        UPDATE entity_to_contact
           SET contact = in_contact_new, description = in_description
         WHERE contact = in_old_contact
               AND entity_id = in_entity_id
               AND contact_class_id = in_old_contact_class;
        return 0;
    END IF;

END;
</programlisting>
      </para>
    </section>

<!-- Function person__save_location(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_code integer, in_old_location_class integer) -->
    <section id="public.function.person-save-location-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-code-integer-in-old-location-class-integer"
             xreflabel="()">
      <title id="public.function.person-save-location-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-code-integer-in-old-location-class-integer-title">
       person__save_location(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_code integer, in_old_location_class integer)
      </title>
      <titleabbrev id="public.function.person-save-location-in-entity-id-integer-in-location-id-integer-in-location-class-integer-in-line-one-text-in-line-two-text-in-line-three-text-in-city-text-in-state-text-in-mail-code-text-in-country-code-integer-in-old-location-class-integer-titleabbrev">
       person__save_location(in_entity_id integer, in_location_id integer, in_location_class integer, in_line_one text, in_line_two text, in_line_three text, in_city text, in_state text, in_mail_code text, in_country_code integer, in_old_location_class integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves a location mapped to the person with the specified information.
Returns the location id saved.
        <programlisting>

    DECLARE
        l_row location;
        l_id INT;
            t_person_id int;
    BEGIN
        SELECT id INTO t_person_id
        FROM person WHERE entity_id = in_entity_id;

    UPDATE entity_to_location
       SET location_class = in_location_class
     WHERE entity_id = in_entity_id
           AND location_class = in_old_location_class
           AND location_id = in_location_id;


    IF NOT FOUND THEN
        -- Create a new one.
        l_id := location_save(
            in_location_id,
            in_line_one,
            in_line_two,
            in_line_three,
            in_city,
                in_state,
                in_mail_code,
                in_country_code);

        INSERT INTO entity_to_location
                (entity_id, location_id, location_class)
        VALUES  (in_entity_id, l_id, in_location_class);
    ELSE
        l_id := location_save(
            in_location_id,
            in_line_one,
            in_line_two,
            in_line_three,
            in_city,
                in_state,
                in_mail_code,
                in_country_code);
        -- Update the old one.
    END IF;
    return l_id;
    END;
</programlisting>
      </para>
    </section>

<!-- Function pnl__customer(in_id integer, in_from_date date, in_to_date date, in_language text) -->
    <section id="public.function.pnl-customer-in-id-integer-in-from-date-date-in-to-date-date-in-language-text"
             xreflabel="()">
      <title id="public.function.pnl-customer-in-id-integer-in-from-date-date-in-to-date-date-in-language-text-title">
       pnl__customer(in_id integer, in_from_date date, in_to_date date, in_language text)
      </title>
      <titleabbrev id="public.function.pnl-customer-in-id-integer-in-from-date-date-in-to-date-date-in-language-text-titleabbrev">
       pnl__customer(in_id integer, in_from_date date, in_to_date date, in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pnl_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH acc_meta AS (
  SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description,
         CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
         ELSE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
         END AS path,
         a.category, &#39;A&#39;::char as account_type, contra, a.gifi_accno,
         gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($4,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
   WHERE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
                          IS NOT NULL
         -- legacy: earn_id not configured (yet)
         OR (NOT EXISTS (SELECT 1 FROM defaults
                         WHERE setting_key = &#39;earn_id&#39;
                           AND value IS NOT NULL)
             AND category IN (&#39;E&#39;, &#39;I&#39;))
),
hdr_meta AS (
   SELECT aht.id, aht.accno,
          coalesce(at.description, aht.description) as description,
          CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
          ELSE array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
          END AS path,
          ahc.derived_category as category,
          &#39;H&#39;::char as account_type, &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($4,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
    WHERE ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NOT NULL
           AND array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
                           IS NOT NULL)
          -- legacy: earn_id not configured; select headings belonging to
          --    selected accounts
          OR ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NULL
              AND EXISTS (SELECT 1 FROM acc_meta
                                  WHERE aht.id = ANY(acc_meta.path)))
),
acc_balance AS (
WITH gl (id) AS
 ( SELECT id FROM ap WHERE approved is true AND entity_credit_account = $1
UNION ALL
   SELECT id FROM ar WHERE approved is true AND entity_credit_account = $1
)
SELECT ac.chart_id AS id, sum(ac.amount) AS balance
  FROM acc_trans ac
  JOIN gl ON ac.trans_id = gl.id
 WHERE ac.approved is true
          AND ($2 IS NULL OR ac.transdate &gt;= $2)
          AND ($3 IS NULL OR ac.transdate &lt;= $3)
 GROUP BY ac.chart_id
   HAVING sum(ac.amount) &lt;&gt; 0.00
 ),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          null::text as gifi, null::text as gifi_description, hm.contra,
          hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          gifi_accno as gifi, gifi_description, am.contra, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function pnl__income_statement_accrual(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text) -->
    <section id="public.function.pnl-income-statement-accrual-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text"
             xreflabel="()">
      <title id="public.function.pnl-income-statement-accrual-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text-title">
       pnl__income_statement_accrual(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text)
      </title>
      <titleabbrev id="public.function.pnl-income-statement-accrual-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text-titleabbrev">
       pnl__income_statement_accrual(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pnl_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH acc_meta AS (
  SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description,
         CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
         ELSE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
         END AS path,
         a.category, &#39;A&#39;::char as account_type, contra, a.gifi_accno,
         gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($5,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
   WHERE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
                          IS NOT NULL
         -- legacy: earn_id not configured (yet)
         OR (NOT EXISTS (SELECT 1 FROM defaults
                         WHERE setting_key = &#39;earn_id&#39;
                               AND value IS NOT NULL)
             AND category IN (&#39;E&#39;, &#39;I&#39;))
),
hdr_meta AS (
   SELECT aht.id, aht.accno,
          coalesce(at.description, aht.description) as description,
          CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
          ELSE array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
          END AS path,
          ahc.derived_category as category,
          &#39;H&#39;::char as account_type, &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($5,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
    WHERE ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NOT NULL
           AND array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
                           IS NOT NULL)
          -- legacy: earn_id not configured; select headings belonging to
          --    selected accounts
          OR ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NULL
              AND EXISTS (SELECT 1 FROM acc_meta
                                  WHERE aht.id = ANY(acc_meta.path)))
),
acc_balance AS (
   WITH RECURSIVE bu_tree (id, parent, path) AS (
      SELECT id, null, row(array[id])::tree_record FROM business_unit
       WHERE id = any($4)
      UNION ALL
      SELECT bu.id, parent, row((path).t || bu.id)::tree_record
        FROM business_unit bu
        JOIN bu_tree ON bu.parent_id = bu_tree.id
   )
   SELECT ac.chart_id AS id, sum(ac.amount) AS balance
     FROM acc_trans ac
    INNER JOIN tx_report gl ON ac.trans_id = gl.id AND gl.approved
     LEFT JOIN (SELECT array_agg(path) AS bu_ids, entry_id
                  FROM business_unit_ac buac
                 INNER JOIN bu_tree ON bu_tree.id = buac.bu_id
                 GROUP BY buac.entry_id) bu
          ON (ac.entry_id = bu.entry_id)
    WHERE ac.approved
          AND ($1 IS NULL OR ac.transdate &gt;= $1)
          AND ($2 IS NULL OR ac.transdate &lt;= $2)
          AND ($4 = &#39;{}&#39;
              OR $4 is null or in_tree($4, bu_ids))
           AND ($3 = &#39;none&#39;
               OR ($3 = &#39;all&#39;
                   AND NOT EXISTS (SELECT * FROM yearend
                                    WHERE trans_id = gl.id))
               OR ($3 = &#39;last&#39;
                   AND NOT EXISTS (SELECT 1 FROM yearend
                                   HAVING max(trans_id) = gl.id))
              )
   GROUP BY ac.chart_id
     HAVING sum(ac.amount) &lt;&gt; 0.00
 ),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          null::text as gifi, null::text as gifi_description, hm.contra,
          hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          gifi_accno as gifi, gifi_description, am.contra, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function pnl__income_statement_cash(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text) -->
    <section id="public.function.pnl-income-statement-cash-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text"
             xreflabel="()">
      <title id="public.function.pnl-income-statement-cash-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text-title">
       pnl__income_statement_cash(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text)
      </title>
      <titleabbrev id="public.function.pnl-income-statement-cash-in-from-date-date-in-to-date-date-in-ignore-yearend-text-in-business-units-integerARRAY-in-language-text-titleabbrev">
       pnl__income_statement_cash(in_from_date date, in_to_date date, in_ignore_yearend text, in_business_units integer[], in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pnl_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH acc_meta AS (
  SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description,
         CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
         ELSE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
         END AS path,
         a.category, &#39;A&#39;::char as account_type, contra, a.gifi_accno,
         gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($5,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
   WHERE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
                          IS NOT NULL
         -- legacy: earn_id not configured (yet)
         OR (NOT EXISTS (SELECT 1 FROM defaults
                         WHERE setting_key = &#39;earn_id&#39;
                           AND value IS NOT NULL)
             AND category IN (&#39;E&#39;, &#39;I&#39;))
),
hdr_meta AS (
   SELECT aht.id, aht.accno,
          coalesce(at.description, aht.description) as description,
          CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
          ELSE array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
          END AS path,
          ahc.derived_category as category,
          &#39;H&#39;::char as account_type, &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($5,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
    WHERE ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NOT NULL
           AND array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
                           IS NOT NULL)
          -- legacy: earn_id not configured; select headings belonging to
          --    selected accounts
          OR ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NULL
              AND EXISTS (SELECT 1 FROM acc_meta
                                  WHERE aht.id = ANY(acc_meta.path)))
),
acc_balance AS (
WITH RECURSIVE bu_tree (id, parent, path) AS (
      SELECT id, null, row(array[id])::tree_record FROM business_unit
       WHERE id = any($4)
      UNION ALL
      SELECT bu.id, parent, row((path).t || bu.id)::tree_record
        FROM business_unit bu
        JOIN bu_tree ON bu.parent_id = bu_tree.id
)
   SELECT ac.chart_id AS id, sum(ac.amount * ca.portion) AS balance
     FROM acc_trans ac
     JOIN tx_report gl ON ac.trans_id = gl.id AND gl.approved
     JOIN (SELECT id, sum(portion) as portion
             FROM cash_impact ca
            WHERE ($1 IS NULL OR ca.transdate &gt;= $1)
                  AND ($2 IS NULL OR ca.transdate &lt;= $2)
           GROUP BY id
          ) ca ON gl.id = ca.id
LEFT JOIN (select array_agg(path) as bu_ids, entry_id
             FROM business_unit_ac buac
             JOIN bu_tree ON bu_tree.id = buac.bu_id
         GROUP BY entry_id) bu
          ON (ac.entry_id = bu.entry_id)
    WHERE ac.approved
          AND ($4 = &#39;{}&#39;
              OR $4 is null or in_tree($4, bu_ids))
          AND ($3 = &#39;none&#39;
               OR ($3 = &#39;all&#39;
                   AND NOT EXISTS (SELECT * FROM yearend WHERE trans_id = gl.id
                   ))
               OR ($3 = &#39;last&#39;
                   AND NOT EXISTS (SELECT 1 FROM yearend
                                   HAVING max(trans_id) = gl.id))
              )
 GROUP BY ac.chart_id
   HAVING sum(ac.amount * ca.portion) &lt;&gt; 0.00
 ),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          null::text as gifi, null::text as gifi_description, hm.contra,
          hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          gifi_accno as gifi, gifi_description, am.contra, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function pnl__invoice(in_id integer, in_language text) -->
    <section id="public.function.pnl-invoice-in-id-integer-in-language-text"
             xreflabel="()">
      <title id="public.function.pnl-invoice-in-id-integer-in-language-text-title">
       pnl__invoice(in_id integer, in_language text)
      </title>
      <titleabbrev id="public.function.pnl-invoice-in-id-integer-in-language-text-titleabbrev">
       pnl__invoice(in_id integer, in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pnl_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH acc_meta AS (
  SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description,
         CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
         ELSE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
         END AS path,
         a.category, &#39;A&#39;::char as account_type, contra, a.gifi_accno,
         gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($2,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
   WHERE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
                          IS NOT NULL
         -- legacy: earn_id not configured (yet)
         OR (NOT EXISTS (SELECT 1 FROM defaults
                         WHERE setting_key = &#39;earn_id&#39;
                           AND value IS NOT NULL)
             AND category IN (&#39;E&#39;, &#39;I&#39;))
),
hdr_meta AS (
   SELECT aht.id, aht.accno,
          coalesce(at.description, aht.description) as description,
          CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
          ELSE array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
          END AS path,
          ahc.derived_category as category,
          &#39;H&#39;::char as account_type, &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($2,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
    WHERE ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NOT NULL
           AND array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
                           IS NOT NULL)
          -- legacy: earn_id not configured; select headings belonging to
          --    selected accounts
          OR ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NULL
              AND EXISTS (SELECT 1 FROM acc_meta
                                  WHERE aht.id = ANY(acc_meta.path)))
),
acc_balance AS (
SELECT ac.chart_id AS id, sum(ac.amount) AS balance
  FROM acc_trans ac
 WHERE ac.approved AND ac.trans_id = $1
 GROUP BY ac.chart_id
 ),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          null::text as gifi, null::text as gifi_description, hm.contra,
          hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          gifi_accno as gifi, gifi_description, am.contra, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function pnl__product(in_from_date date, in_to_date date, in_parts_id integer, in_business_units integer[], in_language text) -->
    <section id="public.function.pnl-product-in-from-date-date-in-to-date-date-in-parts-id-integer-in-business-units-integerARRAY-in-language-text"
             xreflabel="()">
      <title id="public.function.pnl-product-in-from-date-date-in-to-date-date-in-parts-id-integer-in-business-units-integerARRAY-in-language-text-title">
       pnl__product(in_from_date date, in_to_date date, in_parts_id integer, in_business_units integer[], in_language text)
      </title>
      <titleabbrev id="public.function.pnl-product-in-from-date-date-in-to-date-date-in-parts-id-integer-in-business-units-integerARRAY-in-language-text-titleabbrev">
       pnl__product(in_from_date date, in_to_date date, in_parts_id integer, in_business_units integer[], in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pnl_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH acc_meta AS (
  SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description,
         CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
         ELSE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
         END AS path,
         a.category, &#39;A&#39;::char as account_type, contra, a.gifi_accno,
         gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($5,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
   WHERE array_splice_from((SELECT value::int FROM defaults
                             WHERE setting_key = &#39;earn_id&#39;),aht.path)
                          IS NOT NULL
         -- legacy: earn_id not configured (yet)
         OR (NOT EXISTS (SELECT 1 FROM defaults
                         WHERE setting_key = &#39;earn_id&#39;
                           AND value IS NOT NULL)
             AND category IN (&#39;E&#39;, &#39;I&#39;))
),
hdr_meta AS (
   SELECT aht.id, aht.accno,
          coalesce(at.description, aht.description) as description,
          CASE WHEN (SELECT value::int FROM defaults where setting_key = &#39;earn_id&#39;) IS NULL THEN aht.path
          ELSE array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
          END AS path,
          ahc.derived_category as category,
          &#39;H&#39;::char as account_type, &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($5,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
    WHERE ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NOT NULL
           AND array_splice_from((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;),aht.path)
                           IS NOT NULL)
          -- legacy: earn_id not configured; select headings belonging to
          --    selected accounts
          OR ((SELECT value::int FROM defaults
                              WHERE setting_key = &#39;earn_id&#39;) IS NULL
              AND EXISTS (SELECT 1 FROM acc_meta
                                  WHERE aht.id = ANY(acc_meta.path)))
),
acc_balance AS (
   WITH RECURSIVE bu_tree (id, parent, path) AS (
      SELECT id, null, row(array[id])::tree_record FROM business_unit
       WHERE id = any($4)
      UNION ALL
      SELECT bu.id, parent, row((path).t || bu.id)::tree_record
        FROM business_unit bu
        JOIN bu_tree ON bu.parent_id = bu_tree.id
   )
SELECT ac.chart_id AS id, sum(ac.amount) AS balance
     FROM acc_trans ac
     JOIN invoice i ON i.id = ac.invoice_id
     JOIN account_link l ON l.account_id = ac.chart_id
     JOIN ar ON ar.id = ac.trans_id
LEFT JOIN (select as_array(bu.path) as bu_ids, entry_id
             from business_unit_inv bui
             JOIN bu_tree bu ON bui.bu_id = bu.id
         GROUP BY entry_id) bui ON bui.entry_id = i.id
    WHERE i.parts_id = $3
          AND (ac.transdate &gt;= $1 OR $1 IS NULL)
          AND (ac.transdate &lt;= $2 OR $2 IS NULL)
          AND ar.approved
          AND l.description = &#39;IC_expense&#39;
          AND ($4 is null or $4 = &#39;{}&#39; OR in_tree($4, bu_ids))
 GROUP BY ac.chart_id
   HAVING sum(ac.amount) &lt;&gt; 0.00
    UNION
   SELECT ac.chart_id,
          sum(i.sellprice * i.qty * (1 - coalesce(i.discount, 0)))
     FROM invoice i
     JOIN acc_trans ac ON ac.invoice_id = i.id
     JOIN ar ON ar.id = ac.trans_id
LEFT JOIN (select as_array(bu.path) as bu_ids, entry_id
             from business_unit_inv bui
             JOIN bu_tree bu ON bui.bu_id = bu.id
         GROUP BY entry_id) bui ON bui.entry_id = i.id
    WHERE i.parts_id = $3
          AND (ac.transdate &gt;= $1 OR $1 IS NULL)
          AND (ac.transdate &lt;= $2 OR $2 IS NULL)
          AND ar.approved
          AND ($4 is null or $4 = &#39;{}&#39; OR in_tree($4, bu_ids))
 GROUP BY ac.chart_id
   HAVING sum(i.sellprice * i.qty * (1 - coalesce(i.discount, 0))) &lt;&gt; 0.00
 ),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          null::text as gifi, null::text as gifi_description, hm.contra,
          hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          gifi_accno as gifi, gifi_description, am.contra, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function prevent_closed_transactions() -->
    <section id="public.function.prevent-closed-transactions"
             xreflabel="()">
      <title id="public.function.prevent-closed-transactions-title">
       prevent_closed_transactions()
      </title>
      <titleabbrev id="public.function.prevent-closed-transactions-titleabbrev">
       prevent_closed_transactions()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE t_end_date date;
BEGIN
SELECT max(end_date) into t_end_date FROM account_checkpoint;
IF new.transdate &lt;= t_end_date THEN
    RAISE EXCEPTION &#39;Transaction entered into closed period.  Transdate: %&#39;,
                   new.transdate;
END IF;
RETURN new;
END;
</programlisting>
      </para>
    </section>

<!-- Function pricegroup__list() -->
    <section id="public.function.pricegroup-list"
             xreflabel="()">
      <title id="public.function.pricegroup-list-title">
       pricegroup__list()
      </title>
      <titleabbrev id="public.function.pricegroup-list-titleabbrev">
       pricegroup__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pricegroup</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an alphabetically ordered pricegroup list.
        <programlisting>
SELECT * FROM pricegroup ORDER BY pricegroup;
</programlisting>
      </para>
    </section>

<!-- Function pricegroup__search(in_pricegroup text) -->
    <section id="public.function.pricegroup-search-in-pricegroup-text"
             xreflabel="()">
      <title id="public.function.pricegroup-search-in-pricegroup-text-title">
       pricegroup__search(in_pricegroup text)
      </title>
      <titleabbrev id="public.function.pricegroup-search-in-pricegroup-text-titleabbrev">
       pricegroup__search(in_pricegroup text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pricegroup</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
  SELECT * FROM pricegroup
   WHERE $1 IS NULL OR pricegroup ilike $1 || &#39;%&#39;
ORDER BY pricegroup;
</programlisting>
      </para>
    </section>

<!-- Function pricegroups__list() -->
    <section id="public.function.pricegroups-list"
             xreflabel="()">
      <title id="public.function.pricegroups-list-title">
       pricegroups__list()
      </title>
      <titleabbrev id="public.function.pricegroups-list-titleabbrev">
       pricegroups__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF pricegroup</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM pricegroup;
</programlisting>
      </para>
    </section>

<!-- Function pricelist__delete(in_entry_id integer, in_credit_id integer) -->
    <section id="public.function.pricelist-delete-in-entry-id-integer-in-credit-id-integer"
             xreflabel="()">
      <title id="public.function.pricelist-delete-in-entry-id-integer-in-credit-id-integer-title">
       pricelist__delete(in_entry_id integer, in_credit_id integer)
      </title>
      <titleabbrev id="public.function.pricelist-delete-in-entry-id-integer-in-credit-id-integer-titleabbrev">
       pricelist__delete(in_entry_id integer, in_credit_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
delete from partscustomer where entry_id = $1 and credit_id = $2;
delete from partsvendor where entry_id = $1 and credit_id = $2;
select true;
</programlisting>
      </para>
    </section>

<!-- Function pricelist__save(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer, in_qty numeric) -->
    <section id="public.function.pricelist-save-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer-in-qty-numeric"
             xreflabel="()">
      <title id="public.function.pricelist-save-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer-in-qty-numeric-title">
       pricelist__save(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer, in_qty numeric)
      </title>
      <titleabbrev id="public.function.pricelist-save-in-parts-id-integer-in-credit-id-integer-in-pricebreak-numeric-in-price-numeric-in-lead-time-smallint-in-partnumber-text-in-validfrom-date-in-validto-date-in-curr-bpchar-in-entry-id-integer-in-qty-numeric-titleabbrev">
       pricelist__save(in_parts_id integer, in_credit_id integer, in_pricebreak numeric, in_price numeric, in_lead_time smallint, in_partnumber text, in_validfrom date, in_validto date, in_curr bpchar, in_entry_id integer, in_qty numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>eca__pricematrix</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
   retval eca__pricematrix;
   t_insert bool;
   t_entity_class int;

BEGIN

t_insert := false;

SELECT entity_class INTO t_entity_class FROM entity_credit_account
  WHERE id = in_credit_id;

IF t_entity_class = 1 THEN -- VENDOR
    UPDATE partsvendor
       SET lastcost = in_price,
           leadtime = in_lead_time,
           partnumber = in_partnumber,
           curr = in_curr
     WHERE credit_id = in_credit_id AND entry_id = in_entry_id;

    IF NOT FOUND THEN
        INSERT INTO partsvendor
               (parts_id, credit_id, lastcost, leadtime, partnumber, curr)
        VALUES (in_parts_id, in_credit_id, in_price, in_leadtime::int2,
               in_partnumber, in_curr);
    END IF;

    SELECT pv.parts_id, p.partnumber, p.description, pv.credit_id, NULL, NULL,
           pv.lastcost, pv.leadtime::int, pv.partnumber, NULL, NULL, pv.curr,
           pv.entry_id
      INTO retval
      FROM partsvendor pv
      JOIN parts p ON p.id = pv.parts_id
     WHERE parts_id = in_parts_id and credit_id = in_credit_id;

    RETURN retval;

ELSIF t_entity_class = 2 THEN -- CUSTOMER
    UPDATE partscustomer
       SET pricebreak = in_pricebreak,
           sellprice  = in_price,
           validfrom  = in_validfrom,
           validto    = in_validto,
           qty        = in_qty,
           curr       = in_curr
     WHERE entry_id = in_entry_id and credit_id = in_credit_id;

    IF NOT FOUND THEN
        INSERT INTO partscustomer
               (parts_id, credit_id, sellprice, validfrom, validto, curr, qty)
        VALUES (in_parts_id, in_credit_id, in_price, in_validfrom, in_validto,
                in_curr, qty);

        t_insert := true;
    END IF;

    SELECT pc.parts_id, p.partnumber, p.description, pc.credit_id,
           pc.pricebreak, pc.sellprice, NULL, NULL, NULL, pc.validfrom,
           pc.validto, pc.curr, pc.entry_id, qty
      INTO retval
      FROM partscustomer pc
      JOIN parts p on pc.parts_id = p.id
     WHERE entry_id = CASE WHEN t_insert
                           THEN currval(&#39;partscustomer_entry_id_seq&#39;)
                           ELSE in_entry_id
                      END;

    RETURN retval;

ELSE

RAISE EXCEPTION &#39;No valid entity credit account found&#39;;

END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function pricematrix__for_customer(in_credit_id integer, in_parts_id integer, in_transdate date, in_qty numeric, in_currency text) -->
    <section id="public.function.pricematrix-for-customer-in-credit-id-integer-in-parts-id-integer-in-transdate-date-in-qty-numeric-in-currency-text"
             xreflabel="()">
      <title id="public.function.pricematrix-for-customer-in-credit-id-integer-in-parts-id-integer-in-transdate-date-in-qty-numeric-in-currency-text-title">
       pricematrix__for_customer(in_credit_id integer, in_parts_id integer, in_transdate date, in_qty numeric, in_currency text)
      </title>
      <titleabbrev id="public.function.pricematrix-for-customer-in-credit-id-integer-in-parts-id-integer-in-transdate-date-in-qty-numeric-in-currency-text-titleabbrev">
       pricematrix__for_customer(in_credit_id integer, in_parts_id integer, in_transdate date, in_qty numeric, in_currency text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF partscustomer</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT p.*
     FROM partscustomer p
     JOIN entity_credit_account eca ON eca.id = in_credit_id
LEFT JOIN pricegroup pg ON eca.pricegroup_id = pg.id
    WHERE p.parts_id = in_parts_id
        AND coalesce(p.validfrom, in_transdate) &lt;=
            in_transdate
        AND coalesce(p.validto, in_transdate) &gt;=
            in_transdate
        AND (p.credit_id = eca.id OR p.pricegroup_id = pg.id
             OR (p.credit_id is null and p.pricegroup_id is null))
        AND coalesce(qty, 0) &lt;= coalesce(in_qty, 0)
        AND coalesce(p.curr, defaults_get_defaultcurrency()) =
            coalesce(in_currency, defaults_get_defaultcurrency())
  ORDER BY case WHEN p.credit_id = eca.id THEN 1
                WHEN p.pricegroup_id = pg.id THEN 2
                ELSE 3
            end asc, qty desc;

</programlisting>
      </para>
    </section>

<!-- Function pricematrix__for_vendor(in_credit_id integer, in_parts_id integer) -->
    <section id="public.function.pricematrix-for-vendor-in-credit-id-integer-in-parts-id-integer"
             xreflabel="()">
      <title id="public.function.pricematrix-for-vendor-in-credit-id-integer-in-parts-id-integer-title">
       pricematrix__for_vendor(in_credit_id integer, in_parts_id integer)
      </title>
      <titleabbrev id="public.function.pricematrix-for-vendor-in-credit-id-integer-in-parts-id-integer-titleabbrev">
       pricematrix__for_vendor(in_credit_id integer, in_parts_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF partsvendor</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT *
  FROM partsvendor
 WHERE parts_id = in_parts_id
       AND credit_id = in_credit_id;
</programlisting>
      </para>
    </section>

<!-- Function product(numeric) -->
    <section id="public.function.product-numeric"
             xreflabel="()">
      <title id="public.function.product-numeric-title">
       product(numeric)
      </title>
      <titleabbrev id="public.function.product-numeric-titleabbrev">
       product(numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>INTERNAL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>aggregate_dummy</programlisting>
      </para>
    </section>

<!-- Function product(numeric, numeric) -->
    <section id="public.function.product-numeric-numeric"
             xreflabel="()">
      <title id="public.function.product-numeric-numeric-title">
       product(numeric, numeric)
      </title>
      <titleabbrev id="public.function.product-numeric-numeric-titleabbrev">
       product(numeric, numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT $1 * $2;
</programlisting>
      </para>
    </section>

<!-- Function quote_ident_array(text[]) -->
    <section id="public.function.quote-ident-array-textARRAY"
             xreflabel="()">
      <title id="public.function.quote-ident-array-textARRAY-title">
       quote_ident_array(text[])
      </title>
      <titleabbrev id="public.function.quote-ident-array-textARRAY-titleabbrev">
       quote_ident_array(text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text[]</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
   SELECT array_agg(quote_ident(e))
     FROM unnest($1) e;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__account_list() -->
    <section id="public.function.reconciliation-account-list"
             xreflabel="()">
      <title id="public.function.reconciliation-account-list-title">
       reconciliation__account_list()
      </title>
      <titleabbrev id="public.function.reconciliation-account-list-titleabbrev">
       reconciliation__account_list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF recon_accounts</seg>
        </seglistitem>
       </segmentedlist>
 
        returns set of accounts set up for reconciliation.  Currently we pull the
account number and description from the account table.
        <programlisting>
    SELECT DISTINCT
        coa.accno || &#39; &#39; || coa.description as name,
        coa.accno, coa.id as id
    FROM account coa
         JOIN cr_coa_to_account cta ON cta.chart_id = coa.id
    ORDER BY coa.accno;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__add_entry(in_report_id integer, in_scn text, in_type text, in_date timestamp without time zone, in_amount numeric) -->
    <section id="public.function.reconciliation-add-entry-in-report-id-integer-in-scn-text-in-type-text-in-date-timestamp-without-time-zone-in-amount-numeric"
             xreflabel="()">
      <title id="public.function.reconciliation-add-entry-in-report-id-integer-in-scn-text-in-type-text-in-date-timestamp-without-time-zone-in-amount-numeric-title">
       reconciliation__add_entry(in_report_id integer, in_scn text, in_type text, in_date timestamp without time zone, in_amount numeric)
      </title>
      <titleabbrev id="public.function.reconciliation-add-entry-in-report-id-integer-in-scn-text-in-type-text-in-date-timestamp-without-time-zone-in-amount-numeric-titleabbrev">
       reconciliation__add_entry(in_report_id integer, in_scn text, in_type text, in_date timestamp without time zone, in_amount numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function is used for automatically matching entries from an external source
like a bank-produced csv file.

This function is very sensitive to ordering of inputs.  NULL or empty in_scn values MUST be submitted after meaningful scns.  It is also highly recommended
that within each category, one submits in order of amount.  We should therefore
wrap it in another function which can operate on a set, perhaps in 1.4....
It returns the ID of the inserted/updated entry
        <programlisting>

    DECLARE
        in_account int;
        la RECORD;
        t_errorcode INT;
        our_value NUMERIC;
        lid INT;
        in_count int;
        t_scn TEXT;
        t_uid int;
        t_prefix text;
        t_amount numeric;
    BEGIN
        SELECT CASE WHEN a.category in (&#39;A&#39;, &#39;E&#39;) THEN in_amount * -1
                                                  ELSE in_amount
               END into t_amount
          FROM cr_report r JOIN account a ON r.chart_id = a.id
         WHERE r.id = in_report_id;

        SELECT value into t_prefix FROM defaults WHERE setting_key = &#39;check_prefix&#39;;

        t_uid := person__get_my_entity_id();
        IF t_uid IS NULL THEN
                t_uid = robot__get_my_entity_id();
        END IF;
        IF in_scn = &#39;&#39; THEN
                t_scn := NULL;
        ELSIF in_scn !~ &#39;^[0-9]+$&#39; THEN
                t_scn := in_scn;
        ELSE
                t_scn := t_prefix || in_scn;
        END IF;
        IF t_scn IS NOT NULL THEN
                -- could this be changed to update, if not found insert?
                SELECT count(*) INTO in_count FROM cr_report_line
                WHERE scn ilike t_scn AND report_id = in_report_id
                        AND their_balance = 0 AND post_date = in_date;

                IF in_count = 0 THEN
                        -- YLA - Where does our_balance comes from?
                        INSERT INTO cr_report_line
                        (report_id, scn, their_balance, our_balance, clear_time,
                                &quot;user&quot;, trans_type)
                        VALUES
                        (in_report_id, t_scn, t_amount, 0, in_date, t_uid,
                                in_type)
                        RETURNING id INTO lid;
                ELSIF in_count = 1 THEN
                        SELECT id INTO lid
                        WHERE t_scn = scn AND report_id = in_report_id
                                AND their_balance = 0 AND post_date = in_date;
                        UPDATE cr_report_line
                        SET their_balance = t_amount, clear_time = in_date,
                                cleared = true
                        WHERE id = lid;
                ELSE
                        SELECT count(*) INTO in_count FROM cr_report_line
                        WHERE t_scn ilike scn AND report_id = in_report_id
                                AND our_value = t_amount and their_balance = 0
                                AND post_date = in_date;

                        IF in_count = 0 THEN -- no match among many of values
                                SELECT id INTO lid FROM cr_report_line
                                WHERE t_scn ilike scn
                                      AND report_id = in_report_id
                                      AND post_date = in_date
                                ORDER BY our_balance ASC limit 1;

                                UPDATE cr_report_line
                                SET their_balance = t_amount,
                                        clear_time = in_date,
                                        trans_type = in_type,
                                        cleared = true
                                WHERE id = lid;

                        ELSIF in_count = 1 THEN -- EXECT MATCH
                                SELECT id INTO lid FROM cr_report_line
                                WHERE t_scn = scn AND report_id = in_report_id
                                        AND our_value = t_amount
                                        AND their_balance = 0
                                        AND post_date = in_date;
                                UPDATE cr_report_line
                                SET their_balance = t_amount,
                                        trans_type = in_type,
                                        clear_time = in_date,
                                        cleared = true
                                WHERE id = lid;
                        ELSE -- More than one match
                                SELECT id INTO lid FROM cr_report_line
                                WHERE t_scn ilike scn AND report_id = in_report_id
                                        AND our_value = t_amount
                                        AND post_date = in_date
                                ORDER BY id ASC limit 1;

                                UPDATE cr_report_line
                                SET their_balance = t_amount,
                                        trans_type = in_type,
                                        cleared = true,
                                        clear_time = in_date
                                WHERE id = lid;

                        END IF;
                END IF;
        ELSE -- scn IS NULL, check on amount instead
                SELECT count(*) INTO in_count FROM cr_report_line
                WHERE report_id = in_report_id AND our_balance = t_amount
                        AND their_balance = 0 AND post_date = in_date
                        and scn NOT LIKE t_prefix || &#39;%&#39;;

                IF in_count = 0 THEN -- no match
                        INSERT INTO cr_report_line
                        (report_id, scn, their_balance, our_balance, clear_time,
                        &quot;user&quot;, trans_type)
                        VALUES
                        (in_report_id, t_scn, t_amount, 0, in_date, t_uid,
                        in_type)
                        RETURNING id INTO lid;
                ELSIF in_count = 1 THEN -- perfect match
                        SELECT id INTO lid
                        WHERE report_id = in_report_id
                                AND our_balance = t_amount
                                AND their_balance = 0
                                AND post_date = in_date
                                AND in_scn NOT LIKE t_prefix || &#39;%&#39;;
                        UPDATE cr_report_line SET their_balance = t_amount,
                                        trans_type = in_type,
                                        clear_time = in_date,
                                        cleared = true
                        WHERE id = lid;
                ELSE -- more than one match
                        SELECT min(id) INTO lid FROM cr_report_line
                        WHERE report_id = in_report_id AND our_balance = t_amount
                                AND their_balance = 0 AND post_date = in_date
                                AND scn NOT LIKE t_prefix || &#39;%&#39;
                        LIMIT 1;

                        UPDATE cr_report_line SET their_balance = t_amount,
                                        trans_type = in_type,
                                        clear_time = in_date,
                                        cleared = true
                        WHERE id = lid;

                END IF;
        END IF;
        return lid;

    END;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__check(in_end_date date, in_chart_id integer) -->
    <section id="public.function.reconciliation-check-in-end-date-date-in-chart-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-check-in-end-date-date-in-chart-id-integer-title">
       reconciliation__check(in_end_date date, in_chart_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-check-in-end-date-date-in-chart-id-integer-titleabbrev">
       reconciliation__check(in_end_date date, in_chart_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF defaults</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH unapproved_tx as (
     SELECT &#39;unapproved_transactions&#39;::text, count(*)::text
       FROM (SELECT          id::text FROM ar        WHERE approved IS FALSE AND transdate &lt; $1
      UNION  SELECT          id::text FROM ap        WHERE approved IS FALSE AND transdate &lt; $1
      UNION  SELECT          id::text FROM gl        WHERE approved IS FALSE AND transdate &lt; $1
      UNION  SELECT DISTINCT source   FROM acc_trans WHERE approved IS FALSE AND transdate &lt; $1 AND chart_id = $2
            ) tx
),
     unapproved_cr as (
     SELECT &#39;unapproved_reports&#39;::text, count(*)::text
       FROM cr_report
      WHERE end_date &lt; $1 AND approved IS NOT TRUE AND chart_id = $2
)
SELECT * FROM unapproved_tx
UNION SELECT * FROM unapproved_cr;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__delete_my_report(in_report_id integer) -->
    <section id="public.function.reconciliation-delete-my-report-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-delete-my-report-in-report-id-integer-title">
       reconciliation__delete_my_report(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-delete-my-report-in-report-id-integer-titleabbrev">
       reconciliation__delete_my_report(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       This function allows a user to delete his or her own unsubmitted, unapproved
reconciliation reports only.  This is designed to allow a user to back out of
the reconciliation process without cluttering up the search results for others.

        <programlisting>
    DELETE FROM cr_report_line
     WHERE report_id = in_report_id
           AND report_id IN (SELECT id FROM cr_report
                              WHERE entered_username = SESSION_USER
                                    AND submitted IS NOT TRUE
                                    and approved IS NOT TRUE);
    DELETE FROM cr_report
     WHERE id = in_report_id AND entered_username = SESSION_USER
           AND submitted IS NOT TRUE AND approved IS NOT TRUE
    RETURNING TRUE;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__delete_unapproved(in_report_id integer) -->
    <section id="public.function.reconciliation-delete-unapproved-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-delete-unapproved-in-report-id-integer-title">
       reconciliation__delete_unapproved(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-delete-unapproved-in-report-id-integer-titleabbrev">
       reconciliation__delete_unapproved(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       This function deletes any specified unapproved transaction.
        <programlisting>
    DELETE FROM cr_report_line
     WHERE report_id = in_report_id
           AND report_id IN (SELECT id FROM cr_report
                              WHERE approved IS NOT TRUE);
    DELETE FROM cr_report
     WHERE id = in_report_id AND approved IS NOT TRUE
    RETURNING TRUE;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__get_cleared_balance(in_chart_id integer, in_report_date date) -->
    <section id="public.function.reconciliation-get-cleared-balance-in-chart-id-integer-in-report-date-date"
             xreflabel="()">
      <title id="public.function.reconciliation-get-cleared-balance-in-chart-id-integer-in-report-date-date-title">
       reconciliation__get_cleared_balance(in_chart_id integer, in_report_date date)
      </title>
      <titleabbrev id="public.function.reconciliation-get-cleared-balance-in-chart-id-integer-in-report-date-date-titleabbrev">
       reconciliation__get_cleared_balance(in_chart_id integer, in_report_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        Gets the cleared balance of the account specified by chart_id, as of in_report_date.
This is specified in normal format (i.e. positive numbers for debits for asset
and espense accounts, and positive numbers for credits in other accounts

Note that currently contra accounts will show negative balances.
        <programlisting>
    SELECT sum(ac.amount) * CASE WHEN c.category in(&#39;A&#39;, &#39;E&#39;) THEN -1 ELSE 1 END
        FROM account c
        JOIN acc_trans ac ON (ac.chart_id = c.id)
    JOIN (      SELECT id FROM ar WHERE approved
          UNION SELECT id FROM ap WHERE approved
          UNION SELECT id FROM gl WHERE approved
          ) g ON g.id = ac.trans_id
    WHERE c.id = $1 AND cleared
      AND ac.approved IS true
                GROUP BY c.id, c.category;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__get_current_balance(in_account_id integer, in_date date) -->
    <section id="public.function.reconciliation-get-current-balance-in-account-id-integer-in-date-date"
             xreflabel="()">
      <title id="public.function.reconciliation-get-current-balance-in-account-id-integer-in-date-date-title">
       reconciliation__get_current_balance(in_account_id integer, in_date date)
      </title>
      <titleabbrev id="public.function.reconciliation-get-current-balance-in-account-id-integer-in-date-date-titleabbrev">
       reconciliation__get_current_balance(in_account_id integer, in_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>numeric</seg>
        </seglistitem>
       </segmentedlist>
 
        Gets the current balance of all approved transactions against a specific
account.  For asset and expense accounts this is the debit balance, for others
this is the credit balance.
        <programlisting>
        SELECT CASE WHEN (select category FROM account WHERE id = in_account_id)
                        IN (&#39;A&#39;, &#39;E&#39;) THEN sum(a.amount) * -1
                ELSE sum(a.amount) END
        FROM acc_trans a
        JOIN (
                SELECT id FROM ar
                WHERE approved is true
                UNION
                SELECT id FROM ap
                WHERE approved is true
                UNION
                SELECT id FROM gl
                WHERE approved is true
        ) gl ON a.trans_id = gl.id
        WHERE a.approved IS TRUE
                AND a.chart_id = in_account_id
                AND a.transdate &lt;= in_date;

</programlisting>
      </para>
    </section>

<!-- Function reconciliation__new_report_id(in_chart_id integer, in_total numeric, in_end_date date, in_recon_fx boolean) -->
    <section id="public.function.reconciliation-new-report-id-in-chart-id-integer-in-total-numeric-in-end-date-date-in-recon-fx-boolean"
             xreflabel="()">
      <title id="public.function.reconciliation-new-report-id-in-chart-id-integer-in-total-numeric-in-end-date-date-in-recon-fx-boolean-title">
       reconciliation__new_report_id(in_chart_id integer, in_total numeric, in_end_date date, in_recon_fx boolean)
      </title>
      <titleabbrev id="public.function.reconciliation-new-report-id-in-chart-id-integer-in-total-numeric-in-end-date-date-in-recon-fx-boolean-titleabbrev">
       reconciliation__new_report_id(in_chart_id integer, in_total numeric, in_end_date date, in_recon_fx boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Inserts creates a new report and returns the id.
        <programlisting>

    INSERT INTO cr_report(chart_id, their_total, end_date, recon_fx)
    values ($1, $2, $3, $4);
    SELECT currval(&#39;cr_report_id_seq&#39;)::int;

</programlisting>
      </para>
    </section>

<!-- Function reconciliation__pending_transactions(in_report_id integer, in_their_total numeric) -->
    <section id="public.function.reconciliation-pending-transactions-in-report-id-integer-in-their-total-numeric"
             xreflabel="()">
      <title id="public.function.reconciliation-pending-transactions-in-report-id-integer-in-their-total-numeric-title">
       reconciliation__pending_transactions(in_report_id integer, in_their_total numeric)
      </title>
      <titleabbrev id="public.function.reconciliation-pending-transactions-in-report-id-integer-in-their-total-numeric-titleabbrev">
       reconciliation__pending_transactions(in_report_id integer, in_their_total numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Ensures that the list of pending transactions in the report is up to date. 
        <programlisting>

    DECLARE
        gl_row RECORD;
        t_recon_fx BOOL;
        t_chart_id integer;
        t_end_date date;
    BEGIN
       SELECT end_date, recon_fx, chart_id
         INTO t_end_date, t_recon_fx, t_chart_id
         FROM cr_report
        WHERE id = in_report_id;

        INSERT INTO cr_report_line (report_id, scn, their_balance,
                our_balance, &quot;user&quot;, voucher_id, ledger_id, post_date)
        SELECT in_report_id,
               CASE WHEN ac.source IS NULL OR ac.source = &#39;&#39;
                    THEN gl.ref
                    ELSE ac.source END,
               0,
               sum(amount / CASE WHEN t_recon_fx IS NOT TRUE OR gl.table = &#39;gl&#39;
                                 THEN 1
                                 WHEN t_recon_fx and gl.table = &#39;ap&#39;
                                 THEN ex.sell
                                 WHEN t_recon_fx and gl.table = &#39;ar&#39;
                                 THEN ex.buy
                            END) AS amount,
                        (select entity_id from users
                        where username = CURRENT_USER),
                ac.voucher_id, min(ac.entry_id), ac.transdate
        FROM acc_trans ac
        JOIN transactions t on (ac.trans_id = t.id)
        JOIN (select id, entity_credit_account::text as ref, curr,
                     transdate, &#39;ar&#39; as table
                FROM ar where approved
                UNION
              select id, entity_credit_account::text, curr,
                     transdate, &#39;ap&#39; as table
                FROM ap WHERE approved
                UNION
              select id, reference, &#39;&#39;,
                     transdate, &#39;gl&#39; as table
                FROM gl WHERE approved) gl
                ON (gl.table = t.table_name AND gl.id = t.id)
        LEFT JOIN cr_report_line rl ON (rl.report_id = in_report_id
                AND ((rl.ledger_id = ac.entry_id
                        AND ac.voucher_id IS NULL)
                        OR (rl.voucher_id = ac.voucher_id)))
        LEFT JOIN cr_report r ON r.id = in_report_id
        LEFT JOIN exchangerate ex ON gl.transdate = ex.transdate
        WHERE ac.cleared IS FALSE
                AND ac.approved IS TRUE
                AND ac.chart_id = t_chart_id
                AND ac.transdate &lt;= t_end_date
                AND (t_recon_fx is not true
                     OR (t_recon_fx is true
                         AND (gl.table &lt;&gt; &#39;gl&#39;
                              OR ac.fx_transaction IS TRUE)))
                AND (ac.entry_id &gt; coalesce(r.max_ac_id, 0))
        GROUP BY gl.ref, ac.source, ac.transdate,
                ac.memo, ac.voucher_id, gl.table,
                case when gl.table = &#39;gl&#39; then gl.id else 1 end
        HAVING count(rl.id) = 0;

        UPDATE cr_report set updated = date_trunc(&#39;second&#39;, now()),
                their_total = coalesce(in_their_total, their_total),
                max_ac_id = (select max(entry_id) from acc_trans)
        where id = in_report_id;

    RETURN in_report_id;
    END;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__reject_set(in_report_id integer) -->
    <section id="public.function.reconciliation-reject-set-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-reject-set-in-report-id-integer-title">
       reconciliation__reject_set(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-reject-set-in-report-id-integer-titleabbrev">
       reconciliation__reject_set(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
     UPDATE cr_report set submitted = false
      WHERE id = in_report_id
            AND approved is not true
     RETURNING true;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__report_approve(in_report_id integer) -->
    <section id="public.function.reconciliation-report-approve-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-report-approve-in-report-id-integer-title">
       reconciliation__report_approve(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-report-approve-in-report-id-integer-titleabbrev">
       reconciliation__report_approve(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Marks the report approved and marks all cleared transactions in it cleared.
        <programlisting>

    -- Does some basic checks before allowing the approval to go through;
    -- moves the approval to &quot;cr_report_line&quot;, I guess, or some other &quot;final&quot; table.
    --
    -- Pending may just be a single flag in the database to mark that it is
    -- not finalized. Will need to discuss with Chris.

    DECLARE
        current_row RECORD;
        completed cr_report_line;
        total_errors INT;
        in_user TEXT;
        ac_entries int[];
    BEGIN
        in_user := current_user;

        -- so far, so good. Different user, and no errors remain. Therefore,
        -- we can move it to completed reports.
        --
        -- User may not be necessary - I would think it better to use the
        -- in_user, to note who approved the report, than the user who
        -- filed it. This may require clunkier syntax..

        --
        ac_entries := &#39;{}&#39;;
        UPDATE cr_report SET approved = &#39;t&#39;,
                approved_by = person__get_my_entity_id(),
                approved_username = SESSION_USER
        WHERE id = in_report_id;
        IF NOT FOUND THEN
            RAISE EXCEPTION &#39;No report at %.&#39;, $1;
        END IF;

        FOR current_row IN
                SELECT compound_array(entries) AS entries FROM (
                        select as_array(ac.entry_id) as entries
                FROM acc_trans ac
                JOIN transactions t on (ac.trans_id = t.id)
                JOIN (select id, entity_credit_account::text as ref, &#39;ar&#39; as table FROM ar
                UNION select id, entity_credit_account::text,        &#39;ap&#39; as table FROM ap
                UNION select id, reference, &#39;gl&#39; as table FROM gl) gl
                        ON (gl.table = t.table_name AND gl.id = t.id)
                LEFT JOIN cr_report_line rl ON (rl.report_id = in_report_id
                        AND ((rl.ledger_id = ac.entry_id
                                AND ac.voucher_id IS NULL)
                                OR (rl.voucher_id = ac.voucher_id)) and rl.cleared is true)
                WHERE ac.cleared IS FALSE
                        AND ac.chart_id = (select chart_id from cr_report where id = in_report_id)
                GROUP BY gl.ref, ac.source, ac.transdate,
                        ac.memo, ac.voucher_id, gl.table
                HAVING count(rl.report_id) &gt; 0) a
        LOOP
                ac_entries := ac_entries || current_row.entries;
        END LOOP;

        UPDATE acc_trans SET cleared = TRUE
        WHERE entry_id = any(ac_entries);

        return 1;
    END;

</programlisting>
      </para>
    </section>

<!-- Function reconciliation__report_details(in_report_id integer) -->
    <section id="public.function.reconciliation-report-details-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-report-details-in-report-id-integer-title">
       reconciliation__report_details(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-report-details-in-report-id-integer-titleabbrev">
       reconciliation__report_details(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF cr_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the details of the report. 
        <programlisting>

                select * from cr_report_line where report_id = in_report_id
                order by scn, post_date
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__report_details_payee(in_report_id integer) -->
    <section id="public.function.reconciliation-report-details-payee-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-report-details-payee-in-report-id-integer-title">
       reconciliation__report_details_payee(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-report-details-payee-in-report-id-integer-titleabbrev">
       reconciliation__report_details_payee(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF recon_payee</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
                select * from recon_payee where report_id = in_report_id
                order by scn, post_date
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__report_details_payee_with_days(in_report_id integer, in_end_date date) -->
    <section id="public.function.reconciliation-report-details-payee-with-days-in-report-id-integer-in-end-date-date"
             xreflabel="()">
      <title id="public.function.reconciliation-report-details-payee-with-days-in-report-id-integer-in-end-date-date-title">
       reconciliation__report_details_payee_with_days(in_report_id integer, in_end_date date)
      </title>
      <titleabbrev id="public.function.reconciliation-report-details-payee-with-days-in-report-id-integer-in-end-date-date-titleabbrev">
       reconciliation__report_details_payee_with_days(in_report_id integer, in_end_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF recon_payee_days</seg>
        </seglistitem>
       </segmentedlist>
 
        Pulls the payee information for the reconciliation report.
        <programlisting>
BEGIN
            RETURN QUERY
                SELECT rp.id,
                        CASE WHEN in_end_date IS NULL THEN NULL
                        ELSE      in_end_date - clear_time
                        END AS d
                FROM recon_payee rp
                WHERE rp.report_id = in_report_id;

RETURN;
END;</programlisting>
      </para>
    </section>

<!-- Function reconciliation__report_summary(in_report_id integer) -->
    <section id="public.function.reconciliation-report-summary-in-report-id-integer"
             xreflabel="()">
      <title id="public.function.reconciliation-report-summary-in-report-id-integer-title">
       reconciliation__report_summary(in_report_id integer)
      </title>
      <titleabbrev id="public.function.reconciliation-report-summary-in-report-id-integer-titleabbrev">
       reconciliation__report_summary(in_report_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>cr_report</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
        select * from cr_report where id = in_report_id;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__save_set(in_report_id integer, in_line_ids integer[]) -->
    <section id="public.function.reconciliation-save-set-in-report-id-integer-in-line-ids-integerARRAY"
             xreflabel="()">
      <title id="public.function.reconciliation-save-set-in-report-id-integer-in-line-ids-integerARRAY-title">
       reconciliation__save_set(in_report_id integer, in_line_ids integer[])
      </title>
      <titleabbrev id="public.function.reconciliation-save-set-in-report-id-integer-in-line-ids-integerARRAY-titleabbrev">
       reconciliation__save_set(in_report_id integer, in_line_ids integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Sets which lines of the report are cleared.
        <programlisting>
        UPDATE cr_report_line SET cleared = false
        WHERE report_id = in_report_id;

        UPDATE cr_report_line SET cleared = true
        WHERE report_id = in_report_id AND id = ANY(in_line_ids)
        RETURNING TRUE;
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__search(in_date_from date, in_date_to date, in_balance_from numeric, in_balance_to numeric, in_account_id integer, in_submitted boolean, in_approved boolean) -->
    <section id="public.function.reconciliation-search-in-date-from-date-in-date-to-date-in-balance-from-numeric-in-balance-to-numeric-in-account-id-integer-in-submitted-boolean-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.reconciliation-search-in-date-from-date-in-date-to-date-in-balance-from-numeric-in-balance-to-numeric-in-account-id-integer-in-submitted-boolean-in-approved-boolean-title">
       reconciliation__search(in_date_from date, in_date_to date, in_balance_from numeric, in_balance_to numeric, in_account_id integer, in_submitted boolean, in_approved boolean)
      </title>
      <titleabbrev id="public.function.reconciliation-search-in-date-from-date-in-date-to-date-in-balance-from-numeric-in-balance-to-numeric-in-account-id-integer-in-submitted-boolean-in-approved-boolean-titleabbrev">
       reconciliation__search(in_date_from date, in_date_to date, in_balance_from numeric, in_balance_to numeric, in_account_id integer, in_submitted boolean, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF cr_report</seg>
        </seglistitem>
       </segmentedlist>
 
        Searches for reconciliation reports.
NULLs match all values.
in_date_to and in_date_from give a range of reports.  All other inputs are
exact matches.

        <programlisting>
                SELECT r.* FROM cr_report r
                JOIN account c ON (r.chart_id = c.id)
                WHERE
                        (in_date_from IS NULL OR in_date_from &lt;= end_date) and
                        (in_date_to IS NULL OR in_date_to &gt;= end_date) AND
                        (in_balance_from IS NULL
                                or in_balance_from &lt;= their_total ) AND
                        (in_balance_to IS NULL
                                OR in_balance_to &gt;= their_total) AND
                        (in_account_id IS NULL OR in_account_id = chart_id) AND
                        (in_submitted IS NULL or in_submitted = submitted) AND
                        (in_approved IS NULL OR in_approved = approved) AND
                        (r.deleted IS FALSE)
                ORDER BY c.accno, end_date, their_total
</programlisting>
      </para>
    </section>

<!-- Function reconciliation__submit_set(in_report_id integer, in_line_ids integer[]) -->
    <section id="public.function.reconciliation-submit-set-in-report-id-integer-in-line-ids-integerARRAY"
             xreflabel="()">
      <title id="public.function.reconciliation-submit-set-in-report-id-integer-in-line-ids-integerARRAY-title">
       reconciliation__submit_set(in_report_id integer, in_line_ids integer[])
      </title>
      <titleabbrev id="public.function.reconciliation-submit-set-in-report-id-integer-in-line-ids-integerARRAY-titleabbrev">
       reconciliation__submit_set(in_report_id integer, in_line_ids integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Submits a reconciliation report for approval.
in_line_ids is used to specify which report lines are cleared, finalizing the
report.
        <programlisting>
BEGIN
        UPDATE cr_report set submitted = true where id = in_report_id;
        PERFORM reconciliation__save_set(in_report_id, in_line_ids);

        RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function report__aa_outstanding(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer) -->
    <section id="public.function.report-aa-outstanding-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer"
             xreflabel="()">
      <title id="public.function.report-aa-outstanding-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer-title">
       report__aa_outstanding(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer)
      </title>
      <titleabbrev id="public.function.report-aa-outstanding-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer-titleabbrev">
       report__aa_outstanding(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF aa_transactions_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT null::int as id, null::bool as invoice, entity_id, meta_number,
       entity_name, null::date as transdate, count(*)::text as invnumber,
       sum(amount) as amount, sum(netamount) as netamount, sum(tax) as tax,
       sum(paid) as paid, sum(due) as due, max(last_payment) as last_payment,
       null::date as duedate, null::text as notes, null::text as till,
       null::text as salesperson, null::text as manager,
       null::text as shipping_point, null::text as ship_via,
       null::text[] as business_units
  FROM report__aa_outstanding_details($1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
    $11, $12)
 GROUP BY meta_number, entity_name, entity_id;

</programlisting>
      </para>
    </section>

<!-- Function report__aa_outstanding_details(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer) -->
    <section id="public.function.report-aa-outstanding-details-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer"
             xreflabel="()">
      <title id="public.function.report-aa-outstanding-details-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer-title">
       report__aa_outstanding_details(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer)
      </title>
      <titleabbrev id="public.function.report-aa-outstanding-details-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-business-units-integerARRAY-in-ship-via-text-in-on-hold-boolean-in-from-date-date-in-to-date-date-in-partnumber-text-in-parts-id-integer-titleabbrev">
       report__aa_outstanding_details(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_business_units integer[], in_ship_via text, in_on_hold boolean, in_from_date date, in_to_date date, in_partnumber text, in_parts_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF aa_transactions_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT a.id, a.invoice, eeca.id, eca.meta_number, eeca.name, a.transdate,
       a.invnumber, a.amount, a.netamount, a.amount - a.netamount as tax,
       a.amount - p.due as paid, p.due, p.last_payment, a.duedate, a.notes,
       a.till, ee.name, me.name, a.shippingpoint, a.shipvia,
       &#39;{}&#39;::text[] as business_units -- TODO
  FROM (select id, transdate, invnumber, amount, netamount, duedate, notes,
               till, person_id, entity_credit_account, invoice, shippingpoint,
               shipvia, ordnumber, ponumber, description, on_hold, force_closed
          FROM ar
         WHERE in_entity_class = 2 and approved
         UNION
        SELECT id, transdate, invnumber, amount, netamount, duedate, notes,
               null, person_id, entity_credit_account, invoice, shippingpoint,
               shipvia, ordnumber, ponumber, description, on_hold, force_closed
          FROM ap
         WHERE in_entity_class = 1 and approved) a
  LEFT
  JOIN (SELECT trans_id, sum(amount) *
               CASE WHEN in_entity_class = 1 THEN 1 ELSE -1 END AS due,
               max(transdate) as last_payment
          FROM acc_trans ac
          JOIN account_link al ON ac.chart_id = al.account_id
         WHERE approved AND al.description IN (&#39;AR&#39;, &#39;AP&#39;)
               AND (in_to_date is null or transdate &lt;= in_to_date)
      GROUP BY trans_id) p ON p.trans_id = a.id
  JOIN entity_credit_account eca ON a.entity_credit_account = eca.id
  JOIN entity eeca ON eca.entity_id = eeca.id
  LEFT
  JOIN entity_employee ON entity_employee.entity_id = a.person_id
  LEFT
  JOIN entity ee ON entity_employee.entity_id = ee.id
  LEFT
  JOIN entity me ON entity_employee.manager_id = me.id
 WHERE (in_account_id IS NULL
          OR EXISTS (select 1 FROM acc_trans
                      WHERE trans_id = a.id and chart_id = in_account_id))
       AND (in_entity_name IS NULL
           OR eeca.name @@ plainto_tsquery(in_entity_name)
           OR eeca.name ilike &#39;%&#39; || in_entity_name || &#39;%&#39;)
       AND (in_meta_number IS NULL
          OR eca.meta_number ilike in_meta_number || &#39;%&#39;)
       AND (in_employee_id IS NULL OR ee.id = in_employee_id)
       AND (in_ship_via IS NULL
          OR a.shipvia @@ plainto_tsquery(in_ship_via))
       AND (in_on_hold IS NULL OR in_on_hold = a.on_hold)
       AND (in_from_date IS NULL OR a.transdate &gt;= in_from_date)
       AND (in_to_date IS NULL OR a.transdate &lt;= in_to_date)
       AND p.due::numeric(100,2) &lt;&gt; 0
       AND a.force_closed IS NOT TRUE
       AND (in_partnumber IS NULL
          OR EXISTS(SELECT 1 FROM invoice inv
                      JOIN parts ON inv.parts_id = parts.id
                     WHERE inv.trans_id = a.id))
       AND (in_parts_id IS NULL
          OR EXISTS (select 1 FROM invoice
                      WHERE parts_id = in_parts_id AND trans_id = a.id))

</programlisting>
      </para>
    </section>

<!-- Function report__aa_transactions(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_manager_id integer, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_taxable boolean, in_tax_account_id integer, in_open boolean, in_closed boolean, in_approved boolean) -->
    <section id="public.function.report-aa-transactions-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-manager-id-integer-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-taxable-boolean-in-tax-account-id-integer-in-open-boolean-in-closed-boolean-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.report-aa-transactions-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-manager-id-integer-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-taxable-boolean-in-tax-account-id-integer-in-open-boolean-in-closed-boolean-in-approved-boolean-title">
       report__aa_transactions(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_manager_id integer, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_taxable boolean, in_tax_account_id integer, in_open boolean, in_closed boolean, in_approved boolean)
      </title>
      <titleabbrev id="public.function.report-aa-transactions-in-entity-class-integer-in-account-id-integer-in-entity-name-text-in-meta-number-text-in-employee-id-integer-in-manager-id-integer-in-invnumber-text-in-ordnumber-text-in-ponumber-text-in-source-text-in-description-text-in-notes-text-in-shipvia-text-in-from-date-date-in-to-date-date-in-on-hold-boolean-in-taxable-boolean-in-tax-account-id-integer-in-open-boolean-in-closed-boolean-in-approved-boolean-titleabbrev">
       report__aa_transactions(in_entity_class integer, in_account_id integer, in_entity_name text, in_meta_number text, in_employee_id integer, in_manager_id integer, in_invnumber text, in_ordnumber text, in_ponumber text, in_source text, in_description text, in_notes text, in_shipvia text, in_from_date date, in_to_date date, in_on_hold boolean, in_taxable boolean, in_tax_account_id integer, in_open boolean, in_closed boolean, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF aa_transactions_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT a.id, a.invoice, eeca.id, eca.meta_number, eeca.name,
       a.transdate, a.invnumber, a.amount, a.netamount,
       a.amount - a.netamount as tax, a.amount - p.due, p.due, p.last_payment,
       a.duedate, a.notes,
       a.till, eee.name as employee, mee.name as manager, a.shippingpoint,
       a.shipvia, &#39;{}&#39;::text[]

  FROM (select id, transdate, invnumber, amount, netamount, duedate, notes,
               till, person_id, entity_credit_account, invoice, shippingpoint,
               shipvia, ordnumber, ponumber, description, on_hold, force_closed
          FROM ar
         WHERE in_entity_class = 2
               and (in_approved is null or (in_approved = approved))
         UNION
        SELECT id, transdate, invnumber, amount, netamount, duedate, notes,
               null, person_id, entity_credit_account, invoice, shippingpoint,
               shipvia, ordnumber, ponumber, description, on_hold, force_closed
          FROM ap
         WHERE in_entity_class = 1
               and (in_approved is null or (in_approved = approved))) a
  LEFT
  JOIN (select sum(amount) * case when in_entity_class = 1 THEN 1 ELSE -1 END
               as due, trans_id, max(transdate) as last_payment
          FROM acc_trans ac
          JOIN account_link l ON ac.chart_id = l.account_id
         WHERE l.description IN (&#39;AR&#39;, &#39;AP&#39;)
      GROUP BY ac.trans_id
       ) p ON p.trans_id = a.id
  LEFT
  JOIN entity_employee ee ON ee.entity_id = a.person_id
  LEFT
  JOIN entity eee ON eee.id = ee.entity_id
  JOIN entity_credit_account eca ON a.entity_credit_account = eca.id
  JOIN entity eeca ON eca.entity_id = eeca.id
  LEFT
  JOIN entity mee ON ee.manager_id = mee.id
 WHERE (in_account_id IS NULL OR
       EXISTS (select * from acc_trans
               where trans_id = a.id AND chart_id = in_account_id))
       AND (in_entity_name IS NULL
           OR eeca.name ilike &#39;%&#39; || in_entity_name || &#39;%&#39;
           OR eeca.name @@ plainto_tsquery(in_entity_name))
       AND (in_meta_number IS NULL OR eca.meta_number ilike in_meta_number)
       AND (in_employee_id = ee.entity_id OR in_employee_id IS NULL)
       AND (in_manager_id = mee.id OR in_manager_id IS NULL)
       AND (a.invnumber ilike in_invnumber || &#39;%&#39; OR in_invnumber IS NULL)
       AND (a.ordnumber ilike in_ordnumber || &#39;%&#39; OR in_ordnumber IS NULL)
       AND (a.ponumber ilike in_ponumber || &#39;%&#39; OR in_ponumber IS NULL)
       AND (in_source IS NULL OR
           EXISTS (
              SELECT * from acc_trans where trans_id = a.id
                     AND source ilike in_source || &#39;%&#39;
           ))
       AND (in_description IS NULL
              OR a.description @@ plainto_tsquery(in_description))
       AND (in_notes IS NULL OR a.notes @@ plainto_tsquery(in_notes))
       AND (in_shipvia IS NULL OR a.shipvia @@ plainto_tsquery(in_shipvia))
       AND (in_from_date IS NULL OR a.transdate &gt;= in_from_date)
       AND (in_to_date IS NULL OR a.transdate &lt;= in_to_date)
       AND (in_on_hold IS NULL OR in_on_hold = a.on_hold)
       AND (in_taxable IS NULL
            OR (in_taxable
              AND (in_tax_account_id IS NULL
                 OR EXISTS (SELECT 1 FROM acc_trans
                             WHERE trans_id = a.id
                                   AND chart_id = in_tax_account_id)
            ))
            OR (NOT in_taxable
                  AND NOT EXISTS (SELECT 1
                                    FROM acc_trans ac
                                    JOIN account_link al
                                      ON al.account_id = ac.chart_id
                                   WHERE ac.trans_id = a.id
                                         AND al.description ilike &#39;%tax&#39;))
            )
            AND ( -- open/closed handling
              (in_open IS TRUE AND ( a.force_closed IS NOT TRUE AND
                 abs(p.due) &gt; 0.005))                  -- threshold due to
                                                       -- impossibility to
                                                       -- collect below -CT
               OR (in_closed IS TRUE AND ( a.force_closed IS NOT TRUE AND
                 abs(p.due) &gt; 0.005) IS NOT TRUE)
            )

</programlisting>
      </para>
    </section>

<!-- Function report__balance_sheet(in_to_date date, in_language text) -->
    <section id="public.function.report-balance-sheet-in-to-date-date-in-language-text"
             xreflabel="()">
      <title id="public.function.report-balance-sheet-in-to-date-date-in-language-text-title">
       report__balance_sheet(in_to_date date, in_language text)
      </title>
      <titleabbrev id="public.function.report-balance-sheet-in-to-date-date-in-language-text-titleabbrev">
       report__balance_sheet(in_to_date date, in_language text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF balance_sheet_line</seg>
        </seglistitem>
       </segmentedlist>
 
        This produces a balance sheet and the paths (acount numbers) of all headings
necessary; output is generated in the language requested, or in the
users default language if not available. 
        <programlisting>
WITH hdr_meta AS (
   SELECT aht.id, aht.accno, coalesce(at.description, aht.description) as description,
          aht.path,
          ahc.derived_category as category, &#39;H&#39;::char as account_type,
          &#39;f&#39;::boolean as contra
     FROM account_heading_tree aht
    INNER JOIN account_heading_derived_category ahc ON aht.id = ahc.id
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation
                WHERE language_code =
                       coalesce($2,
                         (SELECT up.language
                            FROM user_preference up
                      INNER JOIN users ON up.id = users.id
                           WHERE users.username = SESSION_USER))) at
              ON aht.id = at.trans_id
     WHERE array_endswith((SELECT value::int FROM defaults
                            WHERE setting_key = &#39;earn_id&#39;), aht.path)
           -- legacy (no earn_id) returns all headers
           OR (NOT aht.path @&gt; ARRAY[(SELECT value::int FROM defaults
                                      WHERE setting_key = &#39;earn_id&#39;)])
),
acc_meta AS (
  SELECT a.id, a.accno, coalesce(at.description, a.description) as description,
         aht.path, a.category, &#39;A&#39;::char as account_type, contra,
         a.gifi_accno, gifi.description as gifi_description
     FROM account a
    INNER JOIN account_heading_tree aht on a.heading = aht.id
     LEFT JOIN gifi ON a.gifi_accno = gifi.accno
     LEFT JOIN (SELECT trans_id, description
                  FROM account_translation
                 WHERE language_code =
                        coalesce($2,
                          (SELECT up.language
                             FROM user_preference up
                       INNER JOIN users ON up.id = users.id
                            WHERE users.username = SESSION_USER))) at
               ON a.id = at.trans_id
     WHERE array_endswith((SELECT value::int FROM defaults
                            WHERE setting_key = &#39;earn_id&#39;), aht.path)
           -- legacy (no earn_id) returns all accounts; bug?
           OR (NOT aht.path @&gt; ARRAY[(SELECT value::int FROM defaults
                                      WHERE setting_key = &#39;earn_id&#39;)])
),
acc_balance AS (
   SELECT ac.chart_id as id, sum(ac.amount) as balance
     FROM acc_trans ac
     JOIN tx_report t ON t.approved AND t.id = ac.trans_id
    WHERE ac.transdate &lt;= coalesce($1, (select max(transdate) from acc_trans))
 GROUP BY ac.chart_id
   HAVING sum(ac.amount) &lt;&gt; 0.00
),
hdr_balance AS (
   select ahd.id, sum(balance) as balance
     FROM acc_balance ab
    INNER JOIN account acc ON ab.id = acc.id
    INNER JOIN account_heading_descendant ahd
            ON acc.heading = ahd.descendant_id
    GROUP BY ahd.id
)
   SELECT hm.id, hm.accno, hm.description, hm.account_type, hm.category,
          hm.contra, null::text as gifi_accno,
          null::text as gifi_description, hb.balance, hm.path
     FROM hdr_meta hm
    INNER JOIN hdr_balance hb ON hm.id = hb.id
   UNION
   SELECT am.id, am.accno, am.description, am.account_type, am.category,
          am.contra, am.gifi_accno, am.gifi_description, ab.balance, am.path
     FROM acc_meta am
    INNER JOIN acc_balance ab on am.id = ab.id
</programlisting>
      </para>
    </section>

<!-- Function report__cash_summary(in_from_date date, in_to_date date, in_from_accno text, in_to_accno text) -->
    <section id="public.function.report-cash-summary-in-from-date-date-in-to-date-date-in-from-accno-text-in-to-accno-text"
             xreflabel="()">
      <title id="public.function.report-cash-summary-in-from-date-date-in-to-date-date-in-from-accno-text-in-to-accno-text-title">
       report__cash_summary(in_from_date date, in_to_date date, in_from_accno text, in_to_accno text)
      </title>
      <titleabbrev id="public.function.report-cash-summary-in-from-date-date-in-to-date-date-in-from-accno-text-in-to-accno-text-titleabbrev">
       report__cash_summary(in_from_date date, in_to_date date, in_from_accno text, in_to_accno text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF cash_summary_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT a.id, a.accno, a.is_heading, a.description, t.label,
       sum(CASE WHEN ac.amount &lt; 0 THEN ac.amount * -1 ELSE NULL END),
       sum(CASE WHEN ac.amount &gt; 0 THEN ac.amount ELSE NULL END)
  FROM (select id, accno, false as is_heading, description FROM account
       UNION
        SELECT id, accno, true, description FROM account_heading) a
  LEFT
  JOIN acc_trans ac ON ac.chart_id = a.id
  LEFT
  JOIN (select id, case when table_name ilike &#39;ar&#39; THEN &#39;rcpt&#39;
                        when table_name ilike &#39;ap&#39; THEN &#39;pmt&#39;
                        when table_name ilike &#39;gl&#39; THEN &#39;xfer&#39;
                    END AS label
          FROM transactions) t ON t.id = ac.trans_id
 WHERE accno BETWEEN $3 AND $4
        and ac.transdate BETWEEN $1 AND $2
GROUP BY a.id, a.accno, a.is_heading, a.description, t.label
ORDER BY accno;

</programlisting>
      </para>
    </section>

<!-- Function report__coa() -->
    <section id="public.function.report-coa"
             xreflabel="()">
      <title id="public.function.report-coa-title">
       report__coa()
      </title>
      <titleabbrev id="public.function.report-coa-titleabbrev">
       report__coa()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF coa_entry</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

WITH ac (chart_id, amount) AS (
     SELECT chart_id, sum(amount)
       FROM acc_trans
       JOIN (select id, approved from ar union all
             select id, approved from ap union all
             select id, approved from gl) gl ON gl.id = acc_trans.trans_id
      WHERE acc_trans.approved and gl.approved
      GROUP BY chart_id
),
l(account_id, link) AS (
     SELECT account_id, array_to_string(array_agg(description), &#39;:&#39;)
       FROM account_link
   GROUP BY account_id
),
hh(parent_id) AS (
     SELECT DISTINCT parent_id
       FROM account_heading
),
ha(heading) AS (
     SELECT heading
       FROM account
),
eca(account_id) AS (
    SELECT DISTINCT discount_account_id
      FROM entity_credit_account
    UNION
    SELECT DISTINCT ar_ap_account_id
      FROM entity_credit_account
    UNION
    SELECT DISTINCT cash_account_id
      FROM entity_credit_account
),
ta(account_id) AS (
    SELECT chart_id
      FROM eca_tax
  GROUP BY 1
)
SELECT a.id, a.is_heading, a.accno, a.description, a.gifi_accno,
       CASE WHEN sum(ac.amount) &lt; 0 THEN sum(ac.amount) * -1
            ELSE null::numeric END,
       CASE WHEN sum(ac.amount) &gt; 0 THEN sum(ac.amount)
            ELSE null::numeric END,
       count(ac.*)+count(hh.*)+count(ha.*)+count(eca.*)+count(ta.*), l.link
  FROM (SELECT id, heading, false as is_heading, accno, description, gifi_accno
          FROM account
         UNION
        SELECT id, parent_id, true, accno, description, null::text
          FROM account_heading) a

 LEFT JOIN ac ON ac.chart_id = a.id AND not a.is_heading
 LEFT JOIN l ON l.account_id = a.id AND NOT a.is_heading
 LEFT JOIN hh ON hh.parent_id = a.id AND a.is_heading
 LEFT JOIN ha ON ha.heading = a.id AND a.is_heading
 LEFT JOIN eca ON eca.account_id = a.id AND NOT a.is_heading
 LEFT JOIN ta ON ta.account_id = a.id AND NOT a.is_heading
  GROUP BY a.id, a.is_heading, a.accno, a.description, a.gifi_accno, l.link
  ORDER BY a.accno;

</programlisting>
      </para>
    </section>

<!-- Function report__general_balance(in_from_date date, in_to_date date) -->
    <section id="public.function.report-general-balance-in-from-date-date-in-to-date-date"
             xreflabel="()">
      <title id="public.function.report-general-balance-in-from-date-date-in-to-date-date-title">
       report__general_balance(in_from_date date, in_to_date date)
      </title>
      <titleabbrev id="public.function.report-general-balance-in-from-date-date-in-to-date-date-titleabbrev">
       report__general_balance(in_from_date date, in_to_date date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF general_balance_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT a.id, a.accno, a.description,
      sum(CASE WHEN ac.transdate &lt; $1 THEN abs(amount) ELSE null END),
      sum(CASE WHEN ac.transdate &gt;= $1 AND ac.amount &lt; 0
               THEN ac.amount * -1 ELSE null END),
      SUM(CASE WHEN ac.transdate &gt;= $1 AND ac.amount &gt; 0
               THEN ac.amount ELSE null END),
      SUM(ABS(ac.amount))
 FROM account a
 LEFT
 JOIN acc_trans ac ON ac.chart_id = a.id
 LEFT
 JOIN (select id, approved from ar UNION
       SELECT id, approved from ap UNION
       SELECT id, approved FROM gl) gl ON ac.trans_id = gl.id
WHERE gl.approved and ac.approved
      and ac.transdate &lt;= $2
GROUP BY a.id, a.accno, a.description
ORDER BY a.accno;

</programlisting>
      </para>
    </section>

<!-- Function report__gl(in_reference text, in_accno text, in_category bpchar, in_source text, in_memo text, in_description text, in_from_date date, in_to_date date, in_approved boolean, in_from_amount numeric, in_to_amount numeric, in_business_units integer[]) -->
    <section id="public.function.report-gl-in-reference-text-in-accno-text-in-category-bpchar-in-source-text-in-memo-text-in-description-text-in-from-date-date-in-to-date-date-in-approved-boolean-in-from-amount-numeric-in-to-amount-numeric-in-business-units-integerARRAY"
             xreflabel="()">
      <title id="public.function.report-gl-in-reference-text-in-accno-text-in-category-bpchar-in-source-text-in-memo-text-in-description-text-in-from-date-date-in-to-date-date-in-approved-boolean-in-from-amount-numeric-in-to-amount-numeric-in-business-units-integerARRAY-title">
       report__gl(in_reference text, in_accno text, in_category bpchar, in_source text, in_memo text, in_description text, in_from_date date, in_to_date date, in_approved boolean, in_from_amount numeric, in_to_amount numeric, in_business_units integer[])
      </title>
      <titleabbrev id="public.function.report-gl-in-reference-text-in-accno-text-in-category-bpchar-in-source-text-in-memo-text-in-description-text-in-from-date-date-in-to-date-date-in-approved-boolean-in-from-amount-numeric-in-to-amount-numeric-in-business-units-integerARRAY-titleabbrev">
       report__gl(in_reference text, in_accno text, in_category bpchar, in_source text, in_memo text, in_description text, in_from_date date, in_to_date date, in_approved boolean, in_from_amount numeric, in_to_amount numeric, in_business_units integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF gl_report_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
         retval gl_report_item;
         t_balance numeric;
         t_chart_id int;
BEGIN

IF in_from_date IS NULL THEN
   t_balance := 0;
ELSIF in_accno IS NOT NULL THEN
   SELECT id INTO t_chart_id FROM account WHERE accno  = in_accno;
   t_balance :=
      account__obtain_balance((in_from_date - &#39;1 day&#39;::interval)::date,
                              (select id from account
                                where accno = in_accno));
ELSE
   t_balance := null;
END IF;

FOR retval IN
       WITH RECURSIVE bu_tree (id, path) AS (
            SELECT id, id::text AS path
              FROM business_unit
             WHERE parent_id is null
            UNION
            SELECT bu.id, bu_tree.path || &#39;,&#39; || bu.id
              FROM business_unit bu
              JOIN bu_tree ON bu_tree.id = bu.parent_id
            )
       SELECT g.id, g.type, g.invoice, g.reference, g.description, ac.transdate,
              ac.source, ac.amount, c.accno, c.gifi_accno,
              g.till, ac.cleared, ac.memo, c.description AS accname,
              ac.chart_id, ac.entry_id,
              sum(ac.amount) over (rows unbounded preceding) + t_balance
                as running_balance,
              compound_array(ARRAY[ARRAY[bac.class_id, bac.bu_id]])
         FROM (select id, &#39;gl&#39; as type, false as invoice, reference,
                      description, approved,
                      null::text as till
                 FROM gl
               UNION
               SELECT ar.id, &#39;ar&#39;, invoice, invnumber, e.name, approved, till
                 FROM ar
                 JOIN entity_credit_account eca ON ar.entity_credit_account
                      = eca.id
                 JOIN entity e ON e.id = eca.entity_id
               UNION
               SELECT ap.id, &#39;ap&#39;, invoice, invnumber, e.name, approved,
                      null as till
                 FROM ap
                 JOIN entity_credit_account eca ON ap.entity_credit_account
                      = eca.id
                 JOIN entity e ON e.id = eca.entity_id) g
         JOIN acc_trans ac ON ac.trans_id = g.id
         JOIN account c ON ac.chart_id = c.id
    LEFT JOIN business_unit_ac bac ON ac.entry_id = bac.entry_id
    LEFT JOIN bu_tree ON bac.bu_id = bu_tree.id
        WHERE (g.reference ilike in_reference || &#39;%&#39; or in_reference is null)
              AND (c.accno = in_accno OR in_accno IS NULL)
              AND (ac.source ilike &#39;%&#39; || in_source || &#39;%&#39;
                   OR in_source is null)
              AND (ac.memo ilike &#39;%&#39; || in_memo || &#39;%&#39; OR in_memo is null)
             AND (in_description IS NULL OR
                  g.description
                  @@
                  plainto_tsquery(get_default_lang()::regconfig, in_description))
              AND (transdate BETWEEN in_from_date AND in_to_date
                   OR (transdate &gt;= in_from_date AND  in_to_date IS NULL)
                   OR (transdate &lt;= in_to_date AND in_from_date IS NULL)
                   OR (in_to_date IS NULL AND in_from_date IS NULL))
              AND (in_approved is null OR
                     (in_approved = g.approved AND (ac.approved or in_approved is false)))
              AND (in_from_amount IS NULL OR abs(ac.amount) &gt;= in_from_amount)
              AND (in_to_amount IS NULL OR abs(ac.amount) &lt;= in_to_amount)
              AND (in_category = c.category OR in_category IS NULL)
     GROUP BY g.id, g.type, g.invoice, g.reference, g.description, ac.transdate,
              ac.source, ac.amount, c.accno, c.gifi_accno,
              g.till, ac.cleared, ac.memo, c.description,
              ac.chart_id, ac.entry_id, ac.trans_id
       HAVING in_business_units is null or in_business_units
                &lt;@ compound_array(string_to_array(bu_tree.path, &#39;,&#39;)::int[])
     ORDER BY ac.transdate, ac.trans_id, c.accno
LOOP
   RETURN NEXT retval;
END LOOP;
END;
</programlisting>
      </para>
    </section>

<!-- Function report__incoming_cogs_line(in_date_from date, in_date_to date, in_partnumber text, in_parts_description text) -->
    <section id="public.function.report-incoming-cogs-line-in-date-from-date-in-date-to-date-in-partnumber-text-in-parts-description-text"
             xreflabel="()">
      <title id="public.function.report-incoming-cogs-line-in-date-from-date-in-date-to-date-in-partnumber-text-in-parts-description-text-title">
       report__incoming_cogs_line(in_date_from date, in_date_to date, in_partnumber text, in_parts_description text)
      </title>
      <titleabbrev id="public.function.report-incoming-cogs-line-in-date-from-date-in-date-to-date-in-partnumber-text-in-parts-description-text-titleabbrev">
       report__incoming_cogs_line(in_date_from date, in_date_to date, in_partnumber text, in_parts_description text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF incoming_lot_cogs_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT i.id, a.id, a.invnumber, a.transdate, i.parts_id, p.partnumber,
       i.description, i.qty * -1, i.allocated, p.onhand,
       i.sellprice, i.qty * i.sellprice * -1, i.allocated * i.sellprice
  FROM ap a
  JOIN invoice i ON a.id = i.trans_id
  JOIN parts p ON i.parts_id = p.id
 WHERE p.income_accno_id IS NOT NULL AND p.expense_accno_id IS NOT NULL
       AND (a.transdate &gt;= $1 OR $1 IS NULL)
       AND (a.transdate &lt;= $2 OR $2 IS NULL)
       AND (p.partnumber like $3 || &#39;%&#39; OR $3 IS NULL)
       AND (p.description @@ plainto_tsquery($4)
            OR p.description LIKE &#39;%&#39; || $4 || &#39;%&#39;
            OR $4 IS NULL)
 ORDER BY p.partnumber, a.invnumber;
</programlisting>
      </para>
    </section>

<!-- Function report__invoice_aging_detail(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text) -->
    <section id="public.function.report-invoice-aging-detail-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text"
             xreflabel="()">
      <title id="public.function.report-invoice-aging-detail-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text-title">
       report__invoice_aging_detail(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text)
      </title>
      <titleabbrev id="public.function.report-invoice-aging-detail-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text-titleabbrev">
       report__invoice_aging_detail(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF report_aging_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
                  WITH RECURSIVE bu_tree (id, path) AS (
                SELECT id, id::text AS path
                  FROM business_unit
                 WHERE id = any(in_business_units)
                       OR in_business_units IS NULL
                 UNION
                SELECT bu.id, bu_tree.path || &#39;,&#39; || bu.id
                  FROM business_unit bu
                  JOIN bu_tree ON bu_tree.id = bu.parent_id
                       )
                SELECT c.entity_id, c.meta_number, e.name,
                       e.name as contact_name,
                       a.invnumber, a.transdate, a.till, a.ordnumber,
                       a.ponumber, a.notes,
                       CASE WHEN a.age/30 = 0
                                 THEN (a.sign * sum(ac.amount))
                            ELSE 0 END
                            as c0,
                       CASE WHEN a.age/30 = 1
                                 THEN (a.sign * sum(ac.amount))
                            ELSE 0 END
                            as c30,
                       CASE WHEN a.age/30 = 2
                            THEN (a.sign * sum(ac.amount))
                            ELSE 0 END
                            as c60,
                       CASE WHEN a.age/30 &gt; 2
                            THEN (a.sign * sum(ac.amount))
                            ELSE 0 END
                            as c90,
                       a.duedate, a.id, a.curr,
                       COALESCE((SELECT sell FROM exchangerate ex
                         WHERE a.curr = ex.curr
                              AND ex.transdate = a.transdate), 1)
                       AS exchangerate,
                        (SELECT compound_array(ARRAY[[p.partnumber,
                                        i.description, i.qty::text]])
                                FROM parts p
                                JOIN invoice i ON (i.parts_id = p.id)
                                WHERE i.trans_id = a.id) AS line_items,
                   (coalesce(in_to_date, now())::date - a.transdate) as age
                  FROM (select id, invnumber, till, ordnumber, amount, duedate,
                               curr, ponumber, notes, entity_credit_account,
                               -1 AS sign, transdate, force_closed,
                               CASE WHEN in_use_duedate
                                    THEN coalesce(in_to_date, now())::date
                                         - duedate
                                    ELSE coalesce(in_to_date, now())::date
                                         - transdate
                               END as age
                          FROM ar
                         WHERE in_entity_class = 2
                         UNION
                        SELECT id, invnumber, null, ordnumber, amount, duedate,
                               curr, ponumber, notes, entity_credit_account,
                               1 as sign, transdate, force_closed,
                               CASE WHEN in_use_duedate
                                    THEN coalesce(in_to_date, now())::date
                                         - duedate
                                    ELSE coalesce(in_to_date, now())::date
                                         - transdate
                               END as age
                          FROM ap
                         WHERE in_entity_class = 1) a
                  JOIN acc_trans ac ON ac.trans_id = a.id
                  JOIN account acc ON ac.chart_id = acc.id
                  JOIN account_link acl ON acl.account_id = acc.id
                       AND ((in_entity_class = 1
                              AND acl.description = &#39;AP&#39;)
                           OR (in_entity_class = 2
                              AND acl.description = &#39;AR&#39;))
                  JOIN entity_credit_account c
                       ON a.entity_credit_account = c.id
                  JOIN entity e ON (e.id = c.entity_id)
             LEFT JOIN business_unit_ac buac ON ac.entry_id = buac.entry_id
             LEFT JOIN bu_tree ON buac.bu_id = bu_tree.id
             LEFT JOIN entity_to_location e2l
                       ON e.id = e2l.entity_id
                       AND e2l.location_class = 3
             LEFT JOIN location l ON l.id = e2l.location_id
             LEFT JOIN country ON (country.id = l.country_id)
                 WHERE (e.id = in_entity_id OR in_entity_id IS NULL)
                       AND (in_accno IS NULL or acc.accno = in_accno)
                       AND a.force_closed IS NOT TRUE
                       AND (in_name_part IS NULL
                            OR e.name like &#39;%&#39; || in_name_part || &#39;%&#39;)
              GROUP BY c.entity_id, c.meta_number, e.name,
                       l.line_one, l.line_two, l.line_three,
                       l.city, l.state, l.mail_code, country.name,
                       a.invnumber, a.transdate, a.till, a.ordnumber,
                       a.ponumber, a.notes, a.amount, a.sign,
                       a.duedate, a.id, a.curr, a.age
                HAVING (in_business_units is null or in_business_units
                       &lt;@ compound_array(string_to_array(bu_tree.path,
                                         &#39;,&#39;)::int[]))
                       AND sum(ac.amount::numeric(20,2)) &lt;&gt; 0
              ORDER BY entity_id, curr, transdate, invnumber
</programlisting>
      </para>
    </section>

<!-- Function report__invoice_aging_summary(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text) -->
    <section id="public.function.report-invoice-aging-summary-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text"
             xreflabel="()">
      <title id="public.function.report-invoice-aging-summary-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text-title">
       report__invoice_aging_summary(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text)
      </title>
      <titleabbrev id="public.function.report-invoice-aging-summary-in-entity-id-integer-in-entity-class-integer-in-accno-text-in-to-date-date-in-business-units-integerARRAY-in-use-duedate-boolean-in-name-part-text-titleabbrev">
       report__invoice_aging_summary(in_entity_id integer, in_entity_class integer, in_accno text, in_to_date date, in_business_units integer[], in_use_duedate boolean, in_name_part text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF report_aging_item</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT entity_id, account_number, name, contact_name, null::text, null::date,
       null::text, null::text, null::text, null::text,
       sum(c0), sum(c30), sum(c60), sum(c90), null::date, null::int, curr,
       null::numeric, null::text[], null::int
  FROM report__invoice_aging_detail($1, $2, $3, $4, $5, $6, $7)
 GROUP BY entity_id, account_number, name, contact_name, curr
 ORDER BY account_number
</programlisting>
      </para>
    </section>

<!-- Function report_trial_balance(in_datefrom date, in_dateto date, in_department_id integer, in_project_id integer, in_gifi boolean) -->
    <section id="public.function.report-trial-balance-in-datefrom-date-in-dateto-date-in-department-id-integer-in-project-id-integer-in-gifi-boolean"
             xreflabel="()">
      <title id="public.function.report-trial-balance-in-datefrom-date-in-dateto-date-in-department-id-integer-in-project-id-integer-in-gifi-boolean-title">
       report_trial_balance(in_datefrom date, in_dateto date, in_department_id integer, in_project_id integer, in_gifi boolean)
      </title>
      <titleabbrev id="public.function.report-trial-balance-in-datefrom-date-in-dateto-date-in-department-id-integer-in-project-id-integer-in-gifi-boolean-titleabbrev">
       report_trial_balance(in_datefrom date, in_dateto date, in_department_id integer, in_project_id integer, in_gifi boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF trial_balance_line</seg>
        </seglistitem>
       </segmentedlist>
 
        This is a simple routine to generate trial balances for the full
company, for a project, or for a department.
        <programlisting>
DECLARE out_row trial_balance_line;
BEGIN
        IF in_department_id IS NULL THEN
                FOR out_row IN
                        SELECT c.id, c.accno, c.description,
                                SUM(CASE WHEN ac.transdate &lt; in_datefrom
                                              AND c.category IN (&#39;I&#39;, &#39;L&#39;, &#39;Q&#39;)
                                    THEN ac.amount
                                    ELSE ac.amount * -1
                                    END),
                                SUM(CASE WHEN ac.transdate &gt;= in_date_from
                                              AND ac.amount &gt; 0
                                    THEN ac.amount
                                    ELSE 0 END),
                                SUM(CASE WHEN ac.transdate &gt;= in_date_from
                                              AND ac.amount &lt; 0
                                    THEN ac.amount
                                    ELSE 0 END) * -1,
                                SUM(CASE WHEN ac.transdate &gt;= in_date_from
                                        AND c.charttype IN (&#39;I&#39;)
                                    THEN ac.amount
                                    WHEN ac.transdate &gt;= in_date_from
                                              AND c.category IN (&#39;I&#39;, &#39;L&#39;, &#39;Q&#39;)
                                    THEN ac.amount
                                    ELSE ac.amount * -1
                                    END)
                                FROM acc_trans ac
                                JOIN (select id, approved FROM ap
                                        UNION ALL
                                        select id, approved FROM gl
                                        UNION ALL
                                        select id, approved FROM ar) g
                                        ON (g.id = ac.trans_id)
                                JOIN chart c ON (c.id = ac.chart_id)
                                WHERE ac.transdate &lt;= in_date_to
                                        AND ac.approved AND g.approved
                                        AND (in_project_id IS NULL
                                                OR in_project_id = ac.project_id)
                                GROUP BY c.id, c.accno, c.description
                                ORDER BY c.accno

                LOOP
                        RETURN NEXT out_row;
                END LOOP;
        ELSE
                FOR out_row IN
                        SELECT 1
                LOOP
                        RETURN NEXT out_row;
                END LOOP;
        END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function robot__get(in_entity_id integer) -->
    <section id="public.function.robot-get-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.robot-get-in-entity-id-integer-title">
       robot__get(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.robot-get-in-entity-id-integer-titleabbrev">
       robot__get(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>robot_entity</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT e.id, e.control_code, e.name, e.country_id, c.name,
       p.first_name, p.middle_name, p.last_name, e.entity_class
  FROM entity e
  JOIN country c ON c.id = e.country_id
  JOIN robot p ON p.entity_id = e.id
 WHERE e.id = $1;
</programlisting>
      </para>
    </section>

<!-- Function robot__get_by_cc(in_control_code text) -->
    <section id="public.function.robot-get-by-cc-in-control-code-text"
             xreflabel="()">
      <title id="public.function.robot-get-by-cc-in-control-code-text-title">
       robot__get_by_cc(in_control_code text)
      </title>
      <titleabbrev id="public.function.robot-get-by-cc-in-control-code-text-titleabbrev">
       robot__get_by_cc(in_control_code text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>robot_entity</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT e.id, e.control_code, e.name, e.country_id, c.name,
       p.first_name, p.middle_name, p.last_name, e.entity_class
  FROM entity e
  JOIN country c ON c.id = e.country_id
  JOIN robot p ON p.entity_id = e.id
 WHERE e.control_code = $1;
</programlisting>
      </para>
    </section>

<!-- Function robot__get_my_entity_id() -->
    <section id="public.function.robot-get-my-entity-id"
             xreflabel="()">
      <title id="public.function.robot-get-my-entity-id-title">
       robot__get_my_entity_id()
      </title>
      <titleabbrev id="public.function.robot-get-my-entity-id-titleabbrev">
       robot__get_my_entity_id()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the entity_id of the current, logged in user.
        <programlisting>
        SELECT entity_id from users where username = SESSION_USER OR username = &#39;Migrator&#39;;
</programlisting>
      </para>
    </section>

<!-- Function robot__list_notes(in_entity_id integer) -->
    <section id="public.function.robot-list-notes-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.robot-list-notes-in-entity-id-integer-title">
       robot__list_notes(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.robot-list-notes-in-entity-id-integer-titleabbrev">
       robot__list_notes(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF entity_note</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of notes attached to a robot.
        <programlisting>
                SELECT *
                FROM entity_note
                WHERE ref_key = in_entity_id
                ORDER BY created
</programlisting>
      </para>
    </section>

<!-- Function robot__save(in_entity_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer) -->
    <section id="public.function.robot-save-in-entity-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.robot-save-in-entity-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer-title">
       robot__save(in_entity_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer)
      </title>
      <titleabbrev id="public.function.robot-save-in-entity-id-integer-in-first-name-text-in-middle-name-text-in-last-name-text-in-country-id-integer-titleabbrev">
       robot__save(in_entity_id integer, in_first_name text, in_middle_name text, in_last_name text, in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves the robot with the information specified.  Returns the entity_id
of the record saved.
        <programlisting>

    DECLARE
        e_id int;
        e entity;
        loc location;
        l_id int;
        p_id int;
    BEGIN

    select * into e from entity where id = in_entity_id and entity_class = 3;
    e_id := in_entity_id;

    IF FOUND THEN
        UPDATE entity
           SET name = in_first_name || &#39; &#39; || in_last_name,
               country_id = in_country_id
         WHERE id = in_entity_id;
    ELSE
        INSERT INTO entity (name, entity_class, country_id)
        values (in_first_name || &#39; &#39; || in_last_name, 3, in_country_id);
        e_id := currval(&#39;entity_id_seq&#39;);

    END IF;


    UPDATE robot SET
            first_name = in_first_name,
            last_name = in_last_name,
            middle_name = in_middle_name
    WHERE
            entity_id = in_entity_id;
    IF FOUND THEN
        RETURN in_entity_id;
    ELSE
        -- Do an insert

        INSERT INTO robot (first_name, last_name, entity_id)
        VALUES (in_first_name, in_last_name, e_id);

        RETURN e_id;

    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function save_taxform(in_country_code integer, in_taxform_name text) -->
    <section id="public.function.save-taxform-in-country-code-integer-in-taxform-name-text"
             xreflabel="()">
      <title id="public.function.save-taxform-in-country-code-integer-in-taxform-name-text-title">
       save_taxform(in_country_code integer, in_taxform_name text)
      </title>
      <titleabbrev id="public.function.save-taxform-in-country-code-integer-in-taxform-name-text-titleabbrev">
       save_taxform(in_country_code integer, in_taxform_name text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves tax form information. Returns true or raises exception.
        <programlisting>
        INSERT INTO country_tax_form(country_id, form_name)
        values (in_country_code, in_taxform_name);

        SELECT true;
</programlisting>
      </para>
    </section>

<!-- Function sequence__delete(in_label text) -->
    <section id="public.function.sequence-delete-in-label-text"
             xreflabel="()">
      <title id="public.function.sequence-delete-in-label-text-title">
       sequence__delete(in_label text)
      </title>
      <titleabbrev id="public.function.sequence-delete-in-label-text-titleabbrev">
       sequence__delete(in_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>lsmb_sequence</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DELETE FROM lsmb_sequence where label = $1;

SELECT NULL::lsmb_sequence;
</programlisting>
      </para>
    </section>

<!-- Function sequence__get(in_label text) -->
    <section id="public.function.sequence-get-in-label-text"
             xreflabel="()">
      <title id="public.function.sequence-get-in-label-text-title">
       sequence__get(in_label text)
      </title>
      <titleabbrev id="public.function.sequence-get-in-label-text-titleabbrev">
       sequence__get(in_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>lsmb_sequence</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM lsmb_sequence WHERE label = $1;
</programlisting>
      </para>
    </section>

<!-- Function sequence__increment(in_label text) -->
    <section id="public.function.sequence-increment-in-label-text"
             xreflabel="()">
      <title id="public.function.sequence-increment-in-label-text-title">
       sequence__increment(in_label text)
      </title>
      <titleabbrev id="public.function.sequence-increment-in-label-text-titleabbrev">
       sequence__increment(in_label text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>defaults</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE t_seq lsmb_sequence;
        new_value text;
        retval    defaults;
BEGIN

   SELECT * INTO t_seq FROM lsmb_sequence WHERE label = in_label
          FOR UPDATE;

   new_value := setting__increment_base(t_seq.sequence);

   UPDATE lsmb_sequence SET sequence = new_value WHERE label = in_label;

   retval := row(t_seq.setting_key, t_seq.prefix || new_value || t_seq.suffix);
   return retval;

END;
</programlisting>
      </para>
    </section>

<!-- Function sequence__list() -->
    <section id="public.function.sequence-list"
             xreflabel="()">
      <title id="public.function.sequence-list-title">
       sequence__list()
      </title>
      <titleabbrev id="public.function.sequence-list-titleabbrev">
       sequence__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF lsmb_sequence</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM lsmb_sequence order by label;
</programlisting>
      </para>
    </section>

<!-- Function sequence__list_by_key(in_setting_key text) -->
    <section id="public.function.sequence-list-by-key-in-setting-key-text"
             xreflabel="()">
      <title id="public.function.sequence-list-by-key-in-setting-key-text-title">
       sequence__list_by_key(in_setting_key text)
      </title>
      <titleabbrev id="public.function.sequence-list-by-key-in-setting-key-text-titleabbrev">
       sequence__list_by_key(in_setting_key text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF lsmb_sequence</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM lsmb_sequence where setting_key = $1 order by label;
</programlisting>
      </para>
    </section>

<!-- Function sequence__save(in_label text, in_setting_key text, in_prefix text, in_suffix text, in_sequence text, in_accept_input boolean) -->
    <section id="public.function.sequence-save-in-label-text-in-setting-key-text-in-prefix-text-in-suffix-text-in-sequence-text-in-accept-input-boolean"
             xreflabel="()">
      <title id="public.function.sequence-save-in-label-text-in-setting-key-text-in-prefix-text-in-suffix-text-in-sequence-text-in-accept-input-boolean-title">
       sequence__save(in_label text, in_setting_key text, in_prefix text, in_suffix text, in_sequence text, in_accept_input boolean)
      </title>
      <titleabbrev id="public.function.sequence-save-in-label-text-in-setting-key-text-in-prefix-text-in-suffix-text-in-sequence-text-in-accept-input-boolean-titleabbrev">
       sequence__save(in_label text, in_setting_key text, in_prefix text, in_suffix text, in_sequence text, in_accept_input boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>lsmb_sequence</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval lsmb_sequence;
BEGIN
UPDATE lsmb_sequence
   SET prefix = coalesce(in_prefix, &#39;&#39;),
       suffix = coalesce(in_suffix, &#39;&#39;),
       sequence = coalesce(in_sequence, &#39;1&#39;),
       setting_key = in_setting_key,
       accept_input = coalesce(in_accept_input, false)
 WHERE label = in_label;

IF FOUND THEN
   retval := sequence__get(in_label);
   RETURN retval;
END IF;

INSERT INTO lsmb_sequence(label, setting_key, prefix, suffix, sequence,
                          accept_input)
VALUES (in_label, in_setting_key,
        coalesce(in_prefix, &#39;&#39;),
        coalesce(in_suffix, &#39;&#39;),
        coalesce(in_sequence, &#39;1&#39;),
        coalesce(in_accept_input, false)
);

retval := sequence__get(in_label);
RETURN retval;

end;
</programlisting>
      </para>
    </section>

<!-- Function session_check(in_session_id integer, in_token text) -->
    <section id="public.function.session-check-in-session-id-integer-in-token-text"
             xreflabel="()">
      <title id="public.function.session-check-in-session-id-integer-in-token-text-title">
       session_check(in_session_id integer, in_token text)
      </title>
      <titleabbrev id="public.function.session-check-in-session-id-integer-in-token-text-titleabbrev">
       session_check(in_session_id integer, in_token text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>session</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a session row.  If no session exists, it returns null
        <programlisting>
DECLARE out_row session%ROWTYPE;
BEGIN
        PERFORM * FROM defaults
            WHERE setting_key=&#39;never_logout&#39; and value = &#39;1&#39;;
        IF NOT FOUND THEN
                DELETE FROM session
                WHERE last_used &lt; now() - coalesce((SELECT value FROM defaults
                                                        WHERE setting_key = &#39;session_timeout&#39;)::interval,
                                                   &#39;90 minutes&#39;::interval);
        END IF;

        UPDATE session
           SET last_used = now()
         WHERE session_id = in_session_id
               AND token = in_token
               AND users_id = (select id from users
                        where username = SESSION_USER)
        RETURNING * INTO out_row;

        -- if there is no matching row, return NULL values
        -- note: there is also a failing match when the token doesn&#39;t
        -- match; which might mean a replay attack!
        RETURN out_row;
END;
</programlisting>
      </para>
    </section>

<!-- Function setting__get_currencies() -->
    <section id="public.function.setting-get-currencies"
             xreflabel="()">
      <title id="public.function.setting-get-currencies-title">
       setting__get_currencies()
      </title>
      <titleabbrev id="public.function.setting-get-currencies-titleabbrev">
       setting__get_currencies()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text[]</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns an array of currencies from the defaults table.
        <programlisting>
SELECT string_to_array(value, &#39;:&#39;) from defaults where setting_key = &#39;curr&#39;;
</programlisting>
      </para>
    </section>

<!-- Function setting__increment_base(in_raw_var text) -->
    <section id="public.function.setting-increment-base-in-raw-var-text"
             xreflabel="()">
      <title id="public.function.setting-increment-base-in-raw-var-text-title">
       setting__increment_base(in_raw_var text)
      </title>
      <titleabbrev id="public.function.setting-increment-base-in-raw-var-text-titleabbrev">
       setting__increment_base(in_raw_var text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>character varying</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
declare raw_value VARCHAR;
       base_value VARCHAR;
       increment  INTEGER;
       inc_length INTEGER;
       new_value VARCHAR;
begin
    raw_value := in_raw_var;
    base_value := substring(raw_value from
                                &#39;(&#39; || E&#39;\\&#39; || &#39;d*)(&#39; || E&#39;\\&#39; || &#39;D*|&lt;&#39;
                                    || E&#39;\\&#39; || &#39;?lsmb [^&lt;&gt;] &#39; || E&#39;\\&#39;
                                    || &#39;?&gt;)*$&#39;);
    IF base_value like &#39;0%&#39; THEN
         increment := base_value::integer + 1;
         inc_length := char_length(increment::text);
         new_value := overlay(base_value placing increment::varchar
                              from (char_length(base_value)
                                    - inc_length + 1)
                              for inc_length);
    ELSE
         new_value := base_value::integer + 1;
    END IF;
    return regexp_replace(raw_value, base_value, new_value);
end;
</programlisting>
      </para>
    </section>

<!-- Function setting__set(in_setting_key character varying, in_value character varying) -->
    <section id="public.function.setting-set-in-setting-key-character-varying-in-value-character-varying"
             xreflabel="()">
      <title id="public.function.setting-set-in-setting-key-character-varying-in-value-character-varying-title">
       setting__set(in_setting_key character varying, in_value character varying)
      </title>
      <titleabbrev id="public.function.setting-set-in-setting-key-character-varying-in-value-character-varying-titleabbrev">
       setting__set(in_setting_key character varying, in_value character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        sets a value in the defaults thable and returns true if successful.
        <programlisting>
BEGIN
        UPDATE defaults SET value = in_value WHERE setting_key = in_setting_key;
        IF NOT FOUND THEN
             INSERT INTO defaults (setting_key, value)
                  VALUES (in_setting_key, in_value);
        END IF;
        RETURN TRUE;
END;
</programlisting>
      </para>
    </section>

<!-- Function setting_get(in_key character varying) -->
    <section id="public.function.setting-get-in-key-character-varying"
             xreflabel="()">
      <title id="public.function.setting-get-in-key-character-varying-title">
       setting_get(in_key character varying)
      </title>
      <titleabbrev id="public.function.setting-get-in-key-character-varying-titleabbrev">
       setting_get(in_key character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>defaults</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the value of the setting in the defaults table.
        <programlisting>
SELECT * FROM defaults WHERE setting_key = $1;
</programlisting>
      </para>
    </section>

<!-- Function setting_get_default_accounts() -->
    <section id="public.function.setting-get-default-accounts"
             xreflabel="()">
      <title id="public.function.setting-get-default-accounts-title">
       setting_get_default_accounts()
      </title>
      <titleabbrev id="public.function.setting-get-default-accounts-titleabbrev">
       setting_get_default_accounts()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF defaults</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of settings for default accounts.
        <programlisting>
                SELECT * FROM defaults
                WHERE setting_key like &#39;%accno_id&#39;
                ORDER BY setting_key
</programlisting>
      </para>
    </section>

<!-- Function setting_increment(in_key character varying) -->
    <section id="public.function.setting-increment-in-key-character-varying"
             xreflabel="()">
      <title id="public.function.setting-increment-in-key-character-varying-title">
       setting_increment(in_key character varying)
      </title>
      <titleabbrev id="public.function.setting-increment-in-key-character-varying-titleabbrev">
       setting_increment(in_key character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>character varying</seg>
        </seglistitem>
       </segmentedlist>
 
       This function takes a value for a sequence in the defaults table and increments
it.  Leading zeroes and spaces are preserved as placeholders.  Currently &lt;?lsmb
parsing is not supported in this routine though it may be added at a later date.

        <programlisting>
        UPDATE defaults SET value = setting__increment_base(value)
        WHERE setting_key = in_key
        RETURNING value;

</programlisting>
      </para>
    </section>

<!-- Function sic__list() -->
    <section id="public.function.sic-list"
             xreflabel="()">
      <title id="public.function.sic-list-title">
       sic__list()
      </title>
      <titleabbrev id="public.function.sic-list-titleabbrev">
       sic__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF sic</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM sic ORDER BY code;
</programlisting>
      </para>
    </section>

<!-- Function tax_form__get(in_form_id integer) -->
    <section id="public.function.tax-form-get-in-form-id-integer"
             xreflabel="()">
      <title id="public.function.tax-form-get-in-form-id-integer-title">
       tax_form__get(in_form_id integer)
      </title>
      <titleabbrev id="public.function.tax-form-get-in-form-id-integer-titleabbrev">
       tax_form__get(in_form_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>country_tax_form</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves specified tax form information from the database.
        <programlisting>
SELECT * FROM country_tax_form where id = $1;
</programlisting>
      </para>
    </section>

<!-- Function tax_form__list_all() -->
    <section id="public.function.tax-form-list-all"
             xreflabel="()">
      <title id="public.function.tax-form-list-all-title">
       tax_form__list_all()
      </title>
      <titleabbrev id="public.function.tax-form-list-all-titleabbrev">
       tax_form__list_all()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF tax_form_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a set of all tax forms, ordered by country_id and id
        <programlisting>
SELECT tf.id, tf.form_name, c.name, tf.default_reportable, tf.is_accrual
  FROM country c
  JOIN country_tax_form tf ON c.id = tf.country_id
 ORDER BY country_id, form_name;
</programlisting>
      </para>
    </section>

<!-- Function tax_form__list_ext() -->
    <section id="public.function.tax-form-list-ext"
             xreflabel="()">
      <title id="public.function.tax-form-list-ext-title">
       tax_form__list_ext()
      </title>
      <titleabbrev id="public.function.tax-form-list-ext-titleabbrev">
       tax_form__list_ext()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF taxform_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns a list of tax forms with an added field, country_name, to specify the
name of the country.
        <programlisting>
SELECT t.id, t.form_name, t.country_id, c.name, t.default_reportable,
       t.is_accrual
  FROM country_tax_form t
  JOIN country c ON c.id = t.country_id
 ORDER BY c.name, t.form_name;
</programlisting>
      </para>
    </section>

<!-- Function tax_form__save(in_id integer, in_country_id integer, in_form_name text, in_default_reportable boolean, in_is_accrual boolean) -->
    <section id="public.function.tax-form-save-in-id-integer-in-country-id-integer-in-form-name-text-in-default-reportable-boolean-in-is-accrual-boolean"
             xreflabel="()">
      <title id="public.function.tax-form-save-in-id-integer-in-country-id-integer-in-form-name-text-in-default-reportable-boolean-in-is-accrual-boolean-title">
       tax_form__save(in_id integer, in_country_id integer, in_form_name text, in_default_reportable boolean, in_is_accrual boolean)
      </title>
      <titleabbrev id="public.function.tax-form-save-in-id-integer-in-country-id-integer-in-form-name-text-in-default-reportable-boolean-in-is-accrual-boolean-titleabbrev">
       tax_form__save(in_id integer, in_country_id integer, in_form_name text, in_default_reportable boolean, in_is_accrual boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
       Saves tax form information to the database.
        <programlisting>
BEGIN
        UPDATE country_tax_form
           SET country_id = in_country_id,
               form_name =in_form_name,
               default_reportable = coalesce(in_default_reportable,false),
               is_accrual = coalesce(in_is_accrual, false)
         WHERE id = in_id;

        IF FOUND THEN
           RETURN in_id;
        END IF;

        insert into country_tax_form(country_id,form_name, default_reportable,
                                     is_accrual)
        values (in_country_id, in_form_name,
                coalesce(in_default_reportable, false),
                coalesce(in_is_accrual, false));

        RETURN currval(&#39;country_tax_form_id_seq&#39;);
END;
</programlisting>
      </para>
    </section>

<!-- Function tax_form_details_report(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text) -->
    <section id="public.function.tax-form-details-report-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text"
             xreflabel="()">
      <title id="public.function.tax-form-details-report-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text-title">
       tax_form_details_report(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text)
      </title>
      <titleabbrev id="public.function.tax-form-details-report-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text-titleabbrev">
       tax_form_details_report(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF tax_form_report_detail_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This provides a list of invoices and transactions that a report hits.  This
is intended to allow an organization to adjust what is reported on the 1099
before printing them.
        <programlisting>
              SELECT entity_credit_account.id,
                     company.legal_name, company.entity_id,
                     entity_credit_account.entity_class, entity.control_code,
                     entity_credit_account.meta_number,
                     sum(CASE WHEN gl.amount = 0 then 0
                              when relation = &#39;acc_trans&#39;
                          THEN ac.reportable_amount * pmt.amount
                                / gl.amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 then 0
                              WHEN relation = &#39;invoice&#39;
                          THEN ac.reportable_amount * pmt.amount
                               / gl.amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ar&#39; THEN -1 else 1 end),
                     SUM(CASE WHEN gl.amount = 0 THEN 0
                              ELSE ac.reportable_amount * pmt.amount
                               / gl.amount
                              END
                         * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end
                         * CASE WHEN relation = &#39;invoice&#39; THEN -1 ELSE 1 END),
                     gl.invnumber, gl.duedate::text, gl.id
                FROM (select id, entity_credit_account, invnumber, duedate,
                             amount, transdate, &#39;ar&#39; as class
                        FROM ar
                       UNION
                      select id, entity_credit_account, invnumber, duedate,
                             amount, transdate, &#39;ap&#39; as class
                        FROM ap
                     ) gl
                JOIN (select trans_id, &#39;acc_trans&#39; as relation,
                             sum(amount) as amount,
                             sum(case when atf.reportable then amount else 0
                                 end) as reportable_amount
                        FROM  acc_trans
                   LEFT JOIN ac_tax_form atf
                          ON (acc_trans.entry_id = atf.entry_id)
                       GROUP BY trans_id
                       UNION
                      select trans_id, &#39;invoice&#39; as relation,
                             sum(sellprice * qty) as amount,
                             sum(case when itf.reportable
                                      then sellprice * qty
                                      else 0
                                 end) as reportable_amount
                        FROM invoice
                   LEFT JOIN invoice_tax_form itf
                          ON (invoice.id = itf.invoice_id)
                       GROUP BY trans_id
                     ) ac ON (ac.trans_id = gl.id)
                JOIN entity_credit_account ON (gl.entity_credit_account = entity_credit_account.id)
                JOIN entity ON (entity.id = entity_credit_account.entity_id)
                JOIN company ON (entity.id = company.entity_id)
                JOIN country_tax_form ON (entity_credit_account.taxform_id = country_tax_form.id)
                JOIN (SELECT ac.trans_id, sum(ac.amount) as amount,
                             as_array(entry_id) as entry_ids,
                             as_array(chart_id) as chart_ids,
                             count(*) as num
                        FROM acc_trans ac
                       where chart_id in (select account_id
                                            from account_link
                                           where description like &#39;%paid&#39;)
                          AND transdate BETWEEN in_begin AND in_end
                     group by ac.trans_id
                     ) pmt ON  (pmt.trans_id = gl.id)
                WHERE country_tax_form.id = in_tax_form_id AND meta_number = in_meta_number
                GROUP BY legal_name, meta_number, company.entity_id, entity_credit_account.entity_class, entity.control_code, gl.invnumber, gl.duedate, gl.id, entity_credit_account.id
</programlisting>
      </para>
    </section>

<!-- Function tax_form_details_report_accrual(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text) -->
    <section id="public.function.tax-form-details-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text"
             xreflabel="()">
      <title id="public.function.tax-form-details-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text-title">
       tax_form_details_report_accrual(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text)
      </title>
      <titleabbrev id="public.function.tax-form-details-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date-in-meta-number-text-titleabbrev">
       tax_form_details_report_accrual(in_tax_form_id integer, in_begin date, in_end date, in_meta_number text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF tax_form_report_detail_item</seg>
        </seglistitem>
       </segmentedlist>
 
        This provides a list of invoices and transactions that a report hits.  This
is intended to allow an organization to adjust what is reported on the 1099
before printing them.
        <programlisting>
              SELECT entity_credit_account.id,
                     company.legal_name, company.entity_id,
                     entity_credit_account.entity_class, entity.control_code,
                     entity_credit_account.meta_number,
                     sum(CASE WHEN gl.amount = 0 then 0
                              when relation = &#39;acc_trans&#39;
                          THEN ac.reportable_amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 then 0
                              WHEN relation = &#39;invoice&#39;
                          THEN ac.reportable_amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ar&#39; THEN -1 else 1 end),
                     SUM(CASE WHEN gl.amount = 0
                                   THEN 0
                              ELSE ac.reportable_amount
                              END
                         * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end
                         * CASE WHEN relation = &#39;invoice&#39; THEN -1 ELSE 1 END),
                     gl.invnumber, gl.duedate::text, gl.id
                FROM (select id, entity_credit_account, invnumber, duedate,
                             amount, transdate, &#39;ar&#39; as class
                        FROM ar
                       WHERE transdate BETWEEN in_begin AND in_end
                       UNION
                      select id, entity_credit_account, invnumber, duedate,
                             amount, transdate, &#39;ap&#39; as class
                        FROM ap
                       WHERE transdate BETWEEN in_begin AND in_end
                     ) gl
                JOIN (select trans_id, &#39;acc_trans&#39; as relation,
                             sum(amount) as amount,
                             sum(case when atf.reportable then amount else 0
                                 end) as reportable_amount
                        FROM  acc_trans
                   LEFT JOIN ac_tax_form atf
                          ON (acc_trans.entry_id = atf.entry_id)
                       GROUP BY trans_id
                       UNION
                      select trans_id, &#39;invoice&#39; as relation,
                             sum(sellprice * qty) as amount,
                             sum(case when itf.reportable
                                      then sellprice * qty
                                      else 0
                                 end) as reportable_amount
                        FROM invoice
                   LEFT JOIN invoice_tax_form itf
                          ON (invoice.id = itf.invoice_id)
                       GROUP BY trans_id
                     ) ac ON (ac.trans_id = gl.id)
                JOIN entity_credit_account ON (gl.entity_credit_account = entity_credit_account.id)
                JOIN entity ON (entity.id = entity_credit_account.entity_id)
                JOIN company ON (entity.id = company.entity_id)
                JOIN country_tax_form ON (entity_credit_account.taxform_id = country_tax_form.id)
                WHERE country_tax_form.id = in_tax_form_id AND meta_number = in_meta_number
                GROUP BY legal_name, meta_number, company.entity_id, entity_credit_account.entity_class, entity.control_code, gl.invnumber, gl.duedate, gl.id, entity_credit_account.id
</programlisting>
      </para>
    </section>

<!-- Function tax_form_summary_report(in_tax_form_id integer, in_begin date, in_end date) -->
    <section id="public.function.tax-form-summary-report-in-tax-form-id-integer-in-begin-date-in-end-date"
             xreflabel="()">
      <title id="public.function.tax-form-summary-report-in-tax-form-id-integer-in-begin-date-in-end-date-title">
       tax_form_summary_report(in_tax_form_id integer, in_begin date, in_end date)
      </title>
      <titleabbrev id="public.function.tax-form-summary-report-in-tax-form-id-integer-in-begin-date-in-end-date-titleabbrev">
       tax_form_summary_report(in_tax_form_id integer, in_begin date, in_end date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF tax_form_report_item</seg>
        </seglistitem>
       </segmentedlist>
 
       This provides the total reportable value per vendor.  As per 1099 forms, these
are cash-basis documents and show amounts paid.
        <programlisting>
              SELECT entity_credit_account.id,
                     company.legal_name, company.entity_id,
                     entity_credit_account.entity_class, entity.control_code,
                     entity_credit_account.meta_number,
                     sum(CASE WHEN gl.amount = 0 THEN 0
                              WHEN relation = &#39;acc_trans&#39;
                          THEN ac.reportable_amount * pmt.amount
                                / gl.amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 THEN 0
                              WHEN relation = &#39;invoice&#39;
                          THEN ac.reportable_amount * pmt.amount
                               / gl.amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ar&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 THEN 0
                          ELSE ac.reportable_amount * pmt.amount
                                / gl.amount
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end
                      * CASE WHEN ac.relation = &#39;invoice&#39; then -1 else 1 end)

                FROM (select id, transdate, entity_credit_account, invoice,
                             amount, &#39;ar&#39; as class FROM ar
                       UNION
                      select id, transdate, entity_credit_account, invoice,
                              amount, &#39;ap&#39; as class from ap
                     ) gl
               JOIN (select trans_id, &#39;acc_trans&#39; as relation,
                             sum(amount) as amount,
                             sum(case when atf.reportable then amount else 0
                                 end) as reportable_amount
                        FROM  acc_trans
                    LEFT JOIN ac_tax_form atf
                          ON (acc_trans.entry_id = atf.entry_id)
                       GROUP BY trans_id
                       UNION
                      select trans_id, &#39;invoice&#39; as relation,
                             sum(sellprice * qty) as amount,
                             sum(case when itf.reportable
                                      then sellprice * qty
                                      else 0
                                 end) as reportable_amount
                        FROM invoice
                    LEFT JOIN invoice_tax_form itf
                          ON (invoice.id = itf.invoice_id)
                       GROUP BY trans_id
                     ) ac ON (ac.trans_id = gl.id
                             AND ((gl.invoice is true and ac.relation=&#39;invoice&#39;)
                                  OR (gl.invoice is false
                                     and ac.relation=&#39;acc_trans&#39;)))
                JOIN (SELECT ac.trans_id, sum(ac.amount) as amount,
                             as_array(entry_id) as entry_ids,
                             as_array(chart_id) as chart_ids,
                             count(*) as num
                        FROM acc_trans ac
                       where chart_id in (select account_id
                                            from account_link
                                           where description like &#39;%paid&#39;)
                          AND transdate BETWEEN in_begin AND in_end
                     group by ac.trans_id
                     ) pmt ON  (pmt.trans_id = gl.id)
                JOIN entity_credit_account
                  ON (gl.entity_credit_account = entity_credit_account.id)
                JOIN entity ON (entity.id = entity_credit_account.entity_id)
                JOIN company ON (entity.id = company.entity_id)
                JOIN country_tax_form ON (entity_credit_account.taxform_id = country_tax_form.id)
               WHERE country_tax_form.id = in_tax_form_id
             GROUP BY legal_name, meta_number, company.entity_id, entity_credit_account.entity_class, entity.control_code, entity_credit_account.id
</programlisting>
      </para>
    </section>

<!-- Function tax_form_summary_report_accrual(in_tax_form_id integer, in_begin date, in_end date) -->
    <section id="public.function.tax-form-summary-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date"
             xreflabel="()">
      <title id="public.function.tax-form-summary-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date-title">
       tax_form_summary_report_accrual(in_tax_form_id integer, in_begin date, in_end date)
      </title>
      <titleabbrev id="public.function.tax-form-summary-report-accrual-in-tax-form-id-integer-in-begin-date-in-end-date-titleabbrev">
       tax_form_summary_report_accrual(in_tax_form_id integer, in_begin date, in_end date)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF tax_form_report_item</seg>
        </seglistitem>
       </segmentedlist>
 
       This provides the total reportable value per vendor.  As per 1099 forms, these
are cash-basis documents and show amounts paid.
        <programlisting>
              SELECT entity_credit_account.id,
                     company.legal_name, company.entity_id,
                     entity_credit_account.entity_class, entity.control_code,
                     entity_credit_account.meta_number,
                     sum(CASE WHEN gl.amount = 0 THEN 0
                              WHEN relation = &#39;acc_trans&#39;
                          THEN ac.reportable_amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 THEN 0
                              WHEN relation = &#39;invoice&#39;
                          THEN ac.reportable_amount
                          ELSE 0
                      END * CASE WHEN gl.class = &#39;ar&#39; THEN -1 else 1 end),
                     sum(CASE WHEN gl.amount = 0 THEN 0
                          ELSE ac.reportable_amount
                      END * CASE WHEN gl.class = &#39;ap&#39; THEN -1 else 1 end
                      * CASE WHEN ac.relation = &#39;invoice&#39; then -1 else 1 end)

                FROM (select id, transdate, entity_credit_account, invoice,
                             amount, &#39;ar&#39; as class FROM ar
                       WHERE transdate BETWEEN in_begin AND in_end
                       UNION
                      select id, transdate, entity_credit_account, invoice,
                              amount, &#39;ap&#39; as class from ap
                       WHERE transdate BETWEEN in_begin AND in_end
                     ) gl
               JOIN (select trans_id, &#39;acc_trans&#39; as relation,
                             sum(amount) as amount,
                             sum(case when atf.reportable then amount else 0
                                 end) as reportable_amount
                        FROM  acc_trans
                    LEFT JOIN ac_tax_form atf
                          ON (acc_trans.entry_id = atf.entry_id)
                       GROUP BY trans_id
                       UNION
                      select trans_id, &#39;invoice&#39; as relation,
                             sum(sellprice * qty) as amount,
                             sum(case when itf.reportable
                                      then sellprice * qty
                                      else 0
                                 end) as reportable_amount
                        FROM invoice
                    LEFT JOIN invoice_tax_form itf
                          ON (invoice.id = itf.invoice_id)
                       GROUP BY trans_id
                     ) ac ON (ac.trans_id = gl.id
                             AND ((gl.invoice is true and ac.relation=&#39;invoice&#39;)
                                  OR (gl.invoice is false
                                     and ac.relation=&#39;acc_trans&#39;)))
                JOIN entity_credit_account
                  ON (gl.entity_credit_account = entity_credit_account.id)
                JOIN entity ON (entity.id = entity_credit_account.entity_id)
                JOIN company ON (entity.id = company.entity_id)
                JOIN country_tax_form ON (entity_credit_account.taxform_id = country_tax_form.id)
               WHERE country_tax_form.id = in_tax_form_id
             GROUP BY legal_name, meta_number, company.entity_id, entity_credit_account.entity_class, entity.control_code, entity_credit_account.id
</programlisting>
      </para>
    </section>

<!-- Function template__get(in_template_name text, in_language_code character varying, in_format text) -->
    <section id="public.function.template-get-in-template-name-text-in-language-code-character-varying-in-format-text"
             xreflabel="()">
      <title id="public.function.template-get-in-template-name-text-in-language-code-character-varying-in-format-text-title">
       template__get(in_template_name text, in_language_code character varying, in_format text)
      </title>
      <titleabbrev id="public.function.template-get-in-template-name-text-in-language-code-character-varying-in-format-text-titleabbrev">
       template__get(in_template_name text, in_language_code character varying, in_format text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>template</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM template
 WHERE template_name = $1 AND format = $3 AND
       language_code IS NOT DISTINCT FROM $2;
</programlisting>
      </para>
    </section>

<!-- Function template__get_by_id(in_id integer) -->
    <section id="public.function.template-get-by-id-in-id-integer"
             xreflabel="()">
      <title id="public.function.template-get-by-id-in-id-integer-title">
       template__get_by_id(in_id integer)
      </title>
      <titleabbrev id="public.function.template-get-by-id-in-id-integer-titleabbrev">
       template__get_by_id(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>template</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM template WHERE id = $1;
</programlisting>
      </para>
    </section>

<!-- Function template__list(in_language_code character varying) -->
    <section id="public.function.template-list-in-language-code-character-varying"
             xreflabel="()">
      <title id="public.function.template-list-in-language-code-character-varying-title">
       template__list(in_language_code character varying)
      </title>
      <titleabbrev id="public.function.template-list-in-language-code-character-varying-titleabbrev">
       template__list(in_language_code character varying)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF template</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT * FROM template WHERE language_code IS NOT DISTINCT FROM $1
ORDER BY template_name, format;

</programlisting>
      </para>
    </section>

<!-- Function template__save(in_template_name text, in_language_code character varying, in_template text, in_format text) -->
    <section id="public.function.template-save-in-template-name-text-in-language-code-character-varying-in-template-text-in-format-text"
             xreflabel="()">
      <title id="public.function.template-save-in-template-name-text-in-language-code-character-varying-in-template-text-in-format-text-title">
       template__save(in_template_name text, in_language_code character varying, in_template text, in_format text)
      </title>
      <titleabbrev id="public.function.template-save-in-template-name-text-in-language-code-character-varying-in-template-text-in-format-text-titleabbrev">
       template__save(in_template_name text, in_language_code character varying, in_template text, in_format text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>template</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval template;
BEGIN
   UPDATE template SET template = in_template,
                       last_modified = now()
    WHERE template_name = in_template_name AND format = in_format AND
          language_code IS NOT DISTINCT FROM in_language_code;

   IF FOUND THEN
      retval := template__get(in_template_name, in_language_code, in_format);
      RETURN retval;
   END IF;
   INSERT INTO template (template_name, language_code, template, format)
   VALUES (in_template_name, in_language_code, in_template, in_format);

   retval := template__get(in_template_name, in_language_code, in_format);
   RETURN retval;
END;
</programlisting>
      </para>
    </section>

<!-- Function tg_enforce_perms_eclass() -->
    <section id="public.function.tg-enforce-perms-eclass"
             xreflabel="()">
      <title id="public.function.tg-enforce-perms-eclass-title">
       tg_enforce_perms_eclass()
      </title>
      <titleabbrev id="public.function.tg-enforce-perms-eclass-titleabbrev">
       tg_enforce_perms_eclass()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
   r_eclass entity_class;
BEGIN
IF TG_OP = &#39;DELETE&#39; THEN
   RETURN OLD;
ELSE
   -- super user and database owner (group members)
   -- don&#39;t need access enforcement
   IF pg_has_role((select rolname
                     from pg_database db inner join pg_roles rol
                       on db.datdba = rol.oid
                    where db.datname = current_database()),
                  &#39;USAGE&#39;) IS TRUE THEN
      RETURN NEW;
   END IF;

   SELECT * INTO r_eclass from entity_class WHERE id = NEW.entity_class;
   IF pg_has_role(SESSION_USER,
                  lsmb__role(&#39;contact_class_&#39;
                             || lower(regexp_replace(r_eclass.class,
                                                     &#39; &#39;, &#39;_&#39;))),
                  &#39;USAGE&#39;)
   THEN
      RETURN NEW;
   ELSE
      RAISE EXCEPTION &#39;Access Denied for class&#39;;
   END IF;
END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function timecard__allocate(in_id integer, in_amount numeric) -->
    <section id="public.function.timecard-allocate-in-id-integer-in-amount-numeric"
             xreflabel="()">
      <title id="public.function.timecard-allocate-in-id-integer-in-amount-numeric-title">
       timecard__allocate(in_id integer, in_amount numeric)
      </title>
      <titleabbrev id="public.function.timecard-allocate-in-id-integer-in-amount-numeric-titleabbrev">
       timecard__allocate(in_id integer, in_amount numeric)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>jcitems</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

DECLARE retval jcitems;

BEGIN

UPDATE jcitems SET allocated = allocated + in_amount WHERE id = in_id;

IF NOT FOUND THEN
   RAISE EXCEPTION &#39;timecard not found&#39;;
END IF;

SELECT * INTO retval FROM jcitems WHERE id = in_id;

IF allocated &gt; qty THEN
   RAISE EXCEPTION &#39;Too many allocated&#39;;
END IF;

RETURN retval;

END;
</programlisting>
      </para>
    </section>

<!-- Function timecard__bu_class(in_id integer) -->
    <section id="public.function.timecard-bu-class-in-id-integer"
             xreflabel="()">
      <title id="public.function.timecard-bu-class-in-id-integer-title">
       timecard__bu_class(in_id integer)
      </title>
      <titleabbrev id="public.function.timecard-bu-class-in-id-integer-titleabbrev">
       timecard__bu_class(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>business_unit_class</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * from business_unit_class
 where id in (select class_id from business_unit
               WHERE id in (select business_unit_id from jcitems
                             WHERE id = $1));
</programlisting>
      </para>
    </section>

<!-- Function timecard__get(id integer) -->
    <section id="public.function.timecard-get-id-integer"
             xreflabel="()">
      <title id="public.function.timecard-get-id-integer-title">
       timecard__get(id integer)
      </title>
      <titleabbrev id="public.function.timecard-get-id-integer-titleabbrev">
       timecard__get(id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>jcitems</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting> SELECT * FROM jcitems WHERE id = $1; </programlisting>
      </para>
    </section>

<!-- Function timecard__parts(in_timecard boolean, in_service boolean, in_partnumber text) -->
    <section id="public.function.timecard-parts-in-timecard-boolean-in-service-boolean-in-partnumber-text"
             xreflabel="()">
      <title id="public.function.timecard-parts-in-timecard-boolean-in-service-boolean-in-partnumber-text-title">
       timecard__parts(in_timecard boolean, in_service boolean, in_partnumber text)
      </title>
      <titleabbrev id="public.function.timecard-parts-in-timecard-boolean-in-service-boolean-in-partnumber-text-titleabbrev">
       timecard__parts(in_timecard boolean, in_service boolean, in_partnumber text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF parts</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT *
  FROM parts
 WHERE not obsolete
       AND ($1 OR inventory_accno_id IS NULL)
       AND ($2 OR (income_accno_id IS NOT NULL
             AND inventory_accno_id IS NULL))
       AND ($3 IS NULL OR partnumber like $3 || &#39;%&#39;)
 ORDER BY partnumber;
</programlisting>
      </para>
    </section>

<!-- Function timecard__report(in_business_units integer[], in_partnumber text, in_person_id integer, in_date_from date, in_date_to date, in_open boolean, in_closed boolean, in_jctype integer) -->
    <section id="public.function.timecard-report-in-business-units-integerARRAY-in-partnumber-text-in-person-id-integer-in-date-from-date-in-date-to-date-in-open-boolean-in-closed-boolean-in-jctype-integer"
             xreflabel="()">
      <title id="public.function.timecard-report-in-business-units-integerARRAY-in-partnumber-text-in-person-id-integer-in-date-from-date-in-date-to-date-in-open-boolean-in-closed-boolean-in-jctype-integer-title">
       timecard__report(in_business_units integer[], in_partnumber text, in_person_id integer, in_date_from date, in_date_to date, in_open boolean, in_closed boolean, in_jctype integer)
      </title>
      <titleabbrev id="public.function.timecard-report-in-business-units-integerARRAY-in-partnumber-text-in-person-id-integer-in-date-from-date-in-date-to-date-in-open-boolean-in-closed-boolean-in-jctype-integer-titleabbrev">
       timecard__report(in_business_units integer[], in_partnumber text, in_person_id integer, in_date_from date, in_date_to date, in_open boolean, in_closed boolean, in_jctype integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF timecard_report_line</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
WITH RECURSIVE bu_tree (id, path) AS (
     SELECT id, id::text AS path, control_code, description
       FROM business_unit
      WHERE id = any(in_business_units) OR (in_business_units = &#39;{}&#39; OR in_business_units IS NULL and parent_id IS NULL)
      UNION
     SELECT bu.id, bu_tree.path || &#39;,&#39; || bu.id, bu.control_code, bu.description
       FROM business_unit bu
       JOIN bu_tree ON bu_tree.id = bu.parent_id
)
SELECT j.id, j.description, j.qty, j.allocated, j.checkedin::time as checkedin,
       j.checkedout::time as checkedout, j.checkedin::date as transdate,
       extract(&#39;dow&#39; from j.checkedin) as weekday,
       extract(&#39;week&#39; from j.checkedin) as workweek,
       date_trunc(&#39;week&#39;, j.checkedin)::date as weekstarting,
       p.partnumber, bu.control_code as business_unit_code,
       bu.description AS businessunit_description,
       ee.employeenumber, e.name AS employee, j.parts_id, j.sellprice
  FROM jcitems j
  JOIN parts p ON p.id = j.parts_id
  JOIN person pr ON pr.id = j.person_id
  JOIN entity_employee ee ON ee.entity_id = pr.entity_id
  JOIN entity e ON ee.entity_id = e.id
  LEFT JOIN bu_tree bu ON bu.id = j.business_unit_id
 WHERE (p.partnumber = in_partnumber OR in_partnumber IS NULL)
       AND (j.person_id = in_person_id OR in_person_id IS NULL)
       AND (j.checkedin::date &gt;= in_date_from OR in_date_from IS NULL)
       AND (j.checkedin::date &lt;= in_date_to OR in_date_to IS NULL)
       AND (((j.qty &gt; j.allocated or j.allocated is null)  AND in_open)
            OR (j.qty &lt;= j.allocated AND in_closed))
       AND (j.jctype = in_jctype OR in_jctype is null)
       AND (bu.path IS NOT NULL OR in_business_units = &#39;{}&#39; OR in_business_units IS NULL)
  ORDER BY j.checkedin, bu.description, p.partnumber, e.name
</programlisting>
      </para>
    </section>

<!-- Function timecard__save(in_id integer, in_business_unit_id integer, in_parts_id integer, in_description text, in_qty numeric, in_allocated numeric, in_sellprice numeric, in_fxsellprice numeric, in_serialnumber text, in_checkedin timestamp with time zone, in_checkedout timestamp with time zone, in_person_id integer, in_notes text, in_total numeric, in_non_billable numeric, in_curr bpchar, in_jctype integer) -->
    <section id="public.function.timecard-save-in-id-integer-in-business-unit-id-integer-in-parts-id-integer-in-description-text-in-qty-numeric-in-allocated-numeric-in-sellprice-numeric-in-fxsellprice-numeric-in-serialnumber-text-in-checkedin-timestamp-with-time-zone-in-checkedout-timestamp-with-time-zone-in-person-id-integer-in-notes-text-in-total-numeric-in-non-billable-numeric-in-curr-bpchar-in-jctype-integer"
             xreflabel="()">
      <title id="public.function.timecard-save-in-id-integer-in-business-unit-id-integer-in-parts-id-integer-in-description-text-in-qty-numeric-in-allocated-numeric-in-sellprice-numeric-in-fxsellprice-numeric-in-serialnumber-text-in-checkedin-timestamp-with-time-zone-in-checkedout-timestamp-with-time-zone-in-person-id-integer-in-notes-text-in-total-numeric-in-non-billable-numeric-in-curr-bpchar-in-jctype-integer-title">
       timecard__save(in_id integer, in_business_unit_id integer, in_parts_id integer, in_description text, in_qty numeric, in_allocated numeric, in_sellprice numeric, in_fxsellprice numeric, in_serialnumber text, in_checkedin timestamp with time zone, in_checkedout timestamp with time zone, in_person_id integer, in_notes text, in_total numeric, in_non_billable numeric, in_curr bpchar, in_jctype integer)
      </title>
      <titleabbrev id="public.function.timecard-save-in-id-integer-in-business-unit-id-integer-in-parts-id-integer-in-description-text-in-qty-numeric-in-allocated-numeric-in-sellprice-numeric-in-fxsellprice-numeric-in-serialnumber-text-in-checkedin-timestamp-with-time-zone-in-checkedout-timestamp-with-time-zone-in-person-id-integer-in-notes-text-in-total-numeric-in-non-billable-numeric-in-curr-bpchar-in-jctype-integer-titleabbrev">
       timecard__save(in_id integer, in_business_unit_id integer, in_parts_id integer, in_description text, in_qty numeric, in_allocated numeric, in_sellprice numeric, in_fxsellprice numeric, in_serialnumber text, in_checkedin timestamp with time zone, in_checkedout timestamp with time zone, in_person_id integer, in_notes text, in_total numeric, in_non_billable numeric, in_curr bpchar, in_jctype integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>jcitems</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE retval jcitems;

BEGIN

UPDATE jcitems
   SET description = in_description,
       qty = in_qty,
       allocated = in_allocated,
       serialnumber = in_serialnumber,
       checkedin = in_checkedin,
       checkedout = in_checkedout,
       person_id = coalesce(in_person_id, person__get_my_id()),
       notes = in_notes,
       total = in_total,
       non_billable = in_non_billable
 WHERE id = in_id;

IF FOUND THEN
  SELECT * INTO retval WHERE id = in_id;
  return retval;
END IF;

INSERT INTO jcitems
(business_unit_id, parts_id, description, qty, allocated, sellprice,
  fxsellprice, serialnumber, checkedin, checkedout, person_id, notes,
  total, non_billable, jctype, curr)
VALUES
(in_business_unit_id, in_parts_id, in_description, in_qty, in_allocated,
  in_sellprice, in_fxsellprice, in_serialnumber, in_checkedin, in_checkedout,
  coalesce(in_person_id, person__get_my_id()), in_notes, in_total,
  in_non_billable, in_jctype, in_curr);

SELECT * INTO retval FROM jcitems WHERE id = currval(&#39;jcitems_id_seq&#39;)::int;

RETURN retval;

END;
</programlisting>
      </para>
    </section>

<!-- Function timecard_type__get(in_id integer) -->
    <section id="public.function.timecard-type-get-in-id-integer"
             xreflabel="()">
      <title id="public.function.timecard-type-get-in-id-integer-title">
       timecard_type__get(in_id integer)
      </title>
      <titleabbrev id="public.function.timecard-type-get-in-id-integer-titleabbrev">
       timecard_type__get(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>jctype</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT * FROM jctype where id = $1;

</programlisting>
      </para>
    </section>

<!-- Function timecard_type__list() -->
    <section id="public.function.timecard-type-list"
             xreflabel="()">
      <title id="public.function.timecard-type-list-title">
       timecard_type__list()
      </title>
      <titleabbrev id="public.function.timecard-type-list-titleabbrev">
       timecard_type__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF jctype</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

SELECT * FROM jctype ORDER BY label;

</programlisting>
      </para>
    </section>

<!-- Function to_args(in_base text[], in_args text[]) -->
    <section id="public.function.to-args-in-base-textARRAY-in-args-textARRAY"
             xreflabel="()">
      <title id="public.function.to-args-in-base-textARRAY-in-args-textARRAY-title">
       to_args(in_base text[], in_args text[])
      </title>
      <titleabbrev id="public.function.to-args-in-base-textARRAY-in-args-textARRAY-titleabbrev">
       to_args(in_base text[], in_args text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>text[]</seg>
        </seglistitem>
       </segmentedlist>
 
       
This function takes two arguments.  The first is a one-dimensional array
representing the  base state of the argument array.  The second is a two
element array of {key, value}.

If either of the args is null, it returns the first argument.  Otherwise it
returns the first initial array, concatenated with key || &apos;=&apos; || value.

It primarily exists for the to_args aggregate.

        <programlisting>
SELECT CASE WHEN $2[1] IS NULL OR $2[2] IS NULL THEN $1
            ELSE $1 || ($2[1]::text || &#39;=&#39; || $2[2]::text)
       END;
</programlisting>
      </para>
    </section>

<!-- Function to_args(text[]) -->
    <section id="public.function.to-args-textARRAY"
             xreflabel="()">
      <title id="public.function.to-args-textARRAY-title">
       to_args(text[])
      </title>
      <titleabbrev id="public.function.to-args-textARRAY-titleabbrev">
       to_args(text[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>INTERNAL</seg>
         <seg>text[]</seg>
        </seglistitem>
       </segmentedlist>
 
        Turns a setof ARRAY[key,value] into an
ARRAY[key||&apos;=&apos;||value, key||&apos;=&apos;||value,...]

        <programlisting>aggregate_dummy</programlisting>
      </para>
    </section>

<!-- Function track_global_sequence() -->
    <section id="public.function.track-global-sequence"
             xreflabel="()">
      <title id="public.function.track-global-sequence-title">
       track_global_sequence()
      </title>
      <titleabbrev id="public.function.track-global-sequence-titleabbrev">
       track_global_sequence()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
        This trigger is used to track the id sequence entries across the
transactions table, and with the ar, ap, and gl tables.  This is necessary
because these have not been properly refactored yet.

        <programlisting>
BEGIN
        IF tg_op = &#39;INSERT&#39; THEN
                INSERT INTO transactions (id, table_name, approved)
                VALUES (new.id, TG_RELNAME, new.approved);
        ELSEIF tg_op = &#39;UPDATE&#39; THEN
                IF new.id = old.id AND new.approved = old.approved THEN
                        return new;
                ELSE
                        UPDATE transactions SET id = new.id,
                                                approved = new.approved
                         WHERE id = old.id;
                END IF;
        ELSE
                DELETE FROM transactions WHERE id = old.id;
        END IF;
        RETURN new;
END;
</programlisting>
      </para>
    </section>

<!-- Function trial_balance__generate(in_from_date date, in_to_date date, in_heading integer, in_accounts integer[], in_ignore_yearend text, in_business_units integer[], in_balance_sign integer, in_all_accounts boolean, in_approved boolean) -->
    <section id="public.function.trial-balance-generate-in-from-date-date-in-to-date-date-in-heading-integer-in-accounts-integerARRAY-in-ignore-yearend-text-in-business-units-integerARRAY-in-balance-sign-integer-in-all-accounts-boolean-in-approved-boolean"
             xreflabel="()">
      <title id="public.function.trial-balance-generate-in-from-date-date-in-to-date-date-in-heading-integer-in-accounts-integerARRAY-in-ignore-yearend-text-in-business-units-integerARRAY-in-balance-sign-integer-in-all-accounts-boolean-in-approved-boolean-title">
       trial_balance__generate(in_from_date date, in_to_date date, in_heading integer, in_accounts integer[], in_ignore_yearend text, in_business_units integer[], in_balance_sign integer, in_all_accounts boolean, in_approved boolean)
      </title>
      <titleabbrev id="public.function.trial-balance-generate-in-from-date-date-in-to-date-date-in-heading-integer-in-accounts-integerARRAY-in-ignore-yearend-text-in-business-units-integerARRAY-in-balance-sign-integer-in-all-accounts-boolean-in-approved-boolean-titleabbrev">
       trial_balance__generate(in_from_date date, in_to_date date, in_heading integer, in_accounts integer[], in_ignore_yearend text, in_business_units integer[], in_balance_sign integer, in_all_accounts boolean, in_approved boolean)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>SET OF tb_row</seg>
        </seglistitem>
       </segmentedlist>
 
       Returns a row for each account which has transactions or a starting or
ending balance over the indicated period, except when in_all_accounts
is true, in which case a record is returned for all accounts, even ones
unused over the reporting period.
        <programlisting>
DECLARE
        out_row         tb_row;
        t_roll_forward  date;
        t_cp            account_checkpoint;
        ignore_trans    int[];
        t_start_date    date;
        t_end_date      date;
        t_balance_sign  int;
BEGIN
    IF in_balance_sign IS NULL OR in_balance_sign = 0 THEN
       t_balance_sign = null;
    ELSIF in_balance_sign = -1 OR in_balance_sign = 1 THEN
       t_balance_sign = in_balance_sign;
    ELSE
       RAISE EXCEPTION &#39;Invalid Balance Type&#39;;
    END IF;

    IF in_from_date IS NULL AND in_ignore_yearend = &#39;none&#39; THEN
       SELECT max(end_date) INTO t_roll_forward
         FROM account_checkpoint;
    ELSIF in_from_date IS NULL AND in_ignore_yearend = &#39;last&#39; THEN
       SELECT max(end_date) INTO t_roll_forward
         FROM account_checkpoint
        WHERE end_date &lt; (select max(gl.transdate)
                            FROM gl JOIN yearend y ON y.trans_id = gl.id
                           WHERE y.transdate &lt; coalesce(in_to_date, gl.transdate)
                         );
    ELSIF in_from_date IS NULL THEN
       SELECT min(transdate) - 1 INTO t_roll_forward
         FROM (select min(transdate) as transdate from ar
                union ALL
               select min(transdate) from ap
                union all
               select min(transdate) from gl
                union all
               select min(transdate) from acc_trans) gl;

    ELSE
      SELECT max(end_date) INTO t_roll_forward
         FROM account_checkpoint
        WHERE end_date &lt; in_from_date;
    END IF;

    IF t_roll_forward IS NULL
       OR array_upper(in_business_units, 1) &gt; 0
    THEN
       SELECT min(transdate) - &#39;1 day&#39;::interval
         INTO t_roll_forward
         FROM acc_trans;
    END IF;

    IF in_ignore_yearend = &#39;last&#39; THEN
       SELECT ARRAY[trans_id] INTO ignore_trans FROM yearend
     ORDER BY transdate DESC LIMIT 1;
    ELSIF in_ignore_yearend = &#39;all&#39; THEN
       SELECT array_agg(trans_id) INTO ignore_trans FROM yearend;
    ELSE
       ignore_trans := &#39;{}&#39;;
    END IF;

    IF in_to_date IS NULL THEN
        SELECT max(transdate) INTO t_end_date FROM acc_trans;
    ELSE
        t_end_date := in_to_date;
    END IF;


    RETURN QUERY
       WITH ac (transdate, amount, chart_id) AS (
           WITH RECURSIVE bu_tree (id, path) AS (
            SELECT id, id::text AS path
              FROM business_unit
             WHERE parent_id = any(in_business_units)
            UNION
            SELECT bu.id, bu_tree.path || &#39;,&#39; || bu.id
              FROM business_unit bu
              JOIN bu_tree ON bu_tree.id = bu.parent_id
            )
       SELECT ac.transdate, ac.amount, ac.chart_id
         FROM acc_trans ac
         JOIN (SELECT id, approved FROM ar UNION ALL
               SELECT id, approved FROM ap UNION ALL
               SELECT id, approved FROM gl) gl
                   ON ac.trans_id = gl.id
                     AND (in_approved is null
                          OR (gl.approved = in_approved
                             and (ac.approved OR in_approved is false)))
    LEFT JOIN business_unit_ac buac ON ac.entry_id = buac.entry_id
    LEFT JOIN bu_tree ON buac.bu_id = bu_tree.id
        WHERE ac.transdate BETWEEN t_roll_forward + &#39;1 day&#39;::interval
                                    AND t_end_date
              AND (ignore_trans is null or ac.trans_id &lt;&gt; ALL(ignore_trans))
              AND ((in_business_units = &#39;{}&#39; OR in_business_units IS NULL)
               OR bu_tree.id IS NOT NULL)
       )
       SELECT a.id, a.accno,
         coalesce(at.description, a.description) as description, a.gifi_accno,
         case when in_from_date is null then 0 else
              COALESCE(t_balance_sign,
                      CASE WHEN a.category IN (&#39;A&#39;, &#39;E&#39;) THEN -1 ELSE 1 END )
              * (coalesce(cp.amount, 0)
              + sum(CASE WHEN ac.transdate &lt; coalesce(in_from_date,
                                                      t_roll_forward)
                         THEN ac.amount ELSE 0 END)) end,
              sum(CASE WHEN ac.transdate BETWEEN coalesce(in_from_date,
                                                         t_roll_forward)
                                                 AND coalesce(in_to_date,
                                                         ac.transdate)
                             AND ac.amount &lt; 0 THEN ac.amount * -1 ELSE 0 END) -
              case when in_from_date is null then coalesce(cp.debits, 0) else 0 end,
              sum(CASE WHEN ac.transdate BETWEEN coalesce(in_from_date,
                                                         t_roll_forward)
                                                 AND coalesce(in_to_date,
                                                         ac.transdate)
                             AND ac.amount &gt; 0 THEN ac.amount ELSE 0 END) +
              case when in_from_date is null then coalesce(cp.credits, 0) else 0 end,
              COALESCE(t_balance_sign,
                       CASE WHEN a.category IN (&#39;A&#39;, &#39;E&#39;) THEN -1 ELSE 1 END)
              * (coalesce(cp.amount, 0) + sum(coalesce(ac.amount, 0))),
              CASE WHEN sum(ac.amount) + coalesce(cp.amount, 0) &lt; 0
                   THEN (sum(ac.amount) + coalesce(cp.amount, 0)) * -1
                   ELSE NULL END,
              CASE WHEN sum(ac.amount) + coalesce(cp.amount, 0) &gt; 0
                   THEN sum(ac.amount) + coalesce(cp.amount, 0) ELSE NULL END
         FROM account a
    LEFT JOIN ac ON ac.chart_id = a.id
    LEFT JOIN account_checkpoint cp ON cp.account_id = a.id
              AND end_date = t_roll_forward
    LEFT JOIN (SELECT trans_id, description
                 FROM account_translation at
              INNER JOIN user_preference up ON up.language = at.language_code
              INNER JOIN users ON up.id = users.id
                WHERE users.username = SESSION_USER) at ON a.id = at.trans_id
        WHERE (in_accounts IS NULL OR in_accounts = &#39;{}&#39;
               OR a.id = ANY(in_accounts))
              AND (in_heading IS NULL OR in_heading = a.heading)
     GROUP BY a.id, a.accno, coalesce(at.description, a.description),
              a.category, a.gifi_accno, cp.end_date, cp.account_id, cp.amount,
              cp.debits, cp.credits
       HAVING abs(cp.amount) &gt; 0 or count(ac) &gt; 0 or in_all_accounts
     ORDER BY a.accno;
END;
</programlisting>
      </para>
    </section>

<!-- Function trial_balance__heading_accounts(in_accounts integer[]) -->
    <section id="public.function.trial-balance-heading-accounts-in-accounts-integerARRAY"
             xreflabel="()">
      <title id="public.function.trial-balance-heading-accounts-in-accounts-integerARRAY-title">
       trial_balance__heading_accounts(in_accounts integer[])
      </title>
      <titleabbrev id="public.function.trial-balance-heading-accounts-in-accounts-integerARRAY-titleabbrev">
       trial_balance__heading_accounts(in_accounts integer[])
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF account</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    SELECT * FROM account WHERE id in (SELECT unnest($1));
</programlisting>
      </para>
    </section>

<!-- Function trial_balance__list_headings() -->
    <section id="public.function.trial-balance-list-headings"
             xreflabel="()">
      <title id="public.function.trial-balance-list-headings-title">
       trial_balance__list_headings()
      </title>
      <titleabbrev id="public.function.trial-balance-list-headings-titleabbrev">
       trial_balance__list_headings()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF trial_balance__heading</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
    SELECT id, accno, description, ARRAY( SELECT id FROM account where heading = ah.id) FROM account_heading ah;
</programlisting>
      </para>
    </section>

<!-- Function trigger_parts_short() -->
    <section id="public.function.trigger-parts-short"
             xreflabel="()">
      <title id="public.function.trigger-parts-short-title">
       trigger_parts_short()
      </title>
      <titleabbrev id="public.function.trigger-parts-short-titleabbrev">
       trigger_parts_short()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>trigger</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
BEGIN
  IF NEW.onhand &gt;= NEW.rop THEN
    NOTIFY parts_short;
  END IF;
  RETURN NEW;
END;
</programlisting>
      </para>
    </section>

<!-- Function unlock(in_id integer) -->
    <section id="public.function.unlock-in-id-integer"
             xreflabel="()">
      <title id="public.function.unlock-in-id-integer-title">
       unlock(in_id integer)
      </title>
      <titleabbrev id="public.function.unlock-in-id-integer-titleabbrev">
       unlock(in_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Releases a pessimistic locks against a transaction, if that transaciton, as
identified by in_id exists, and if  it is locked by the current session.
These locks are again only advisory, and the application may choose to handle
them or not.

Returns true if the transaction was unlocked by this routine, false
otherwise.
        <programlisting>
BEGIN
    UPDATE transactions SET locked_by = NULL WHERE id = in_id
           AND locked_by IN (SELECT session_id FROM session WHERE users_id =
                (SELECT id FROM users WHERE username = SESSION_USER));
    RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function unlock_all() -->
    <section id="public.function.unlock-all"
             xreflabel="()">
      <title id="public.function.unlock-all-title">
       unlock_all()
      </title>
      <titleabbrev id="public.function.unlock-all-titleabbrev">
       unlock_all()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
       Releases all pessimistic locks against transactions.  These locks are again
only advisory, and the application may choose to handle them or not.

Returns true if any transactions were unlocked, false otherwise.
        <programlisting>
BEGIN
    UPDATE transactions SET locked_by = NULL
    where locked_by IN
          (select session_id from session WHERE users_id =
                  (SELECT id FROM users WHERE username = SESSION_USER));

    RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function user__change_password(in_new_password text) -->
    <section id="public.function.user-change-password-in-new-password-text"
             xreflabel="()">
      <title id="public.function.user-change-password-in-new-password-text-title">
       user__change_password(in_new_password text)
      </title>
      <titleabbrev id="public.function.user-change-password-in-new-password-text-titleabbrev">
       user__change_password(in_new_password text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Allows a user to change his or her own password.  The password is set to
expire setting_get(&apos;password_duration&apos;) days after the password change.
        <programlisting>
DECLARE
        t_expires timestamp;
        t_password_duration text;
BEGIN
    SELECT value INTO t_password_duration FROM defaults
     WHERE setting_key = &#39;password_duration&#39;;
    IF t_password_duration IS NULL or t_password_duration=&#39;&#39; THEN
        t_expires := &#39;infinity&#39;;
    ELSE
        t_expires := now()
                     + (t_password_duration::numeric::text || &#39; days&#39;)::interval;
    END IF;


    UPDATE users SET notify_password = DEFAULT where username = SESSION_USER;

    EXECUTE &#39;ALTER USER &#39; || quote_ident(SESSION_USER) ||
            &#39; with ENCRYPTED password &#39; || quote_literal(in_new_password) ||
                 &#39; VALID UNTIL &#39;|| quote_literal(t_expires);
    return 1;
END;
</programlisting>
      </para>
    </section>

<!-- Function user__check_my_expiration() -->
    <section id="public.function.user-check-my-expiration"
             xreflabel="()">
      <title id="public.function.user-check-my-expiration-title">
       user__check_my_expiration()
      </title>
      <titleabbrev id="public.function.user-check-my-expiration-titleabbrev">
       user__check_my_expiration()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>interval</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the time when password of the current logged in user is set to
expire.
        <programlisting>
DECLARE
    outval interval;
BEGIN
    SELECT CASE WHEN isfinite(rolvaliduntil) is not true THEN &#39;1 year&#39;::interval
                ELSE rolvaliduntil - now() END AS expiration INTO outval
    FROM pg_roles WHERE rolname = SESSION_USER;
    RETURN outval;
end;
</programlisting>
      </para>
    </section>

<!-- Function user__expires_soon() -->
    <section id="public.function.user-expires-soon"
             xreflabel="()">
      <title id="public.function.user-expires-soon-title">
       user__expires_soon()
      </title>
      <titleabbrev id="public.function.user-expires-soon-titleabbrev">
       user__expires_soon()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns true if the password of the current logged in user is set to expire
within on week.
        <programlisting>
   SELECT user__check_my_expiration() &lt; &#39;1 week&#39;;
</programlisting>
      </para>
    </section>

<!-- Function user__get_all_users() -->
    <section id="public.function.user-get-all-users"
             xreflabel="()">
      <title id="public.function.user-get-all-users-title">
       user__get_all_users()
      </title>
      <titleabbrev id="public.function.user-get-all-users-titleabbrev">
       user__get_all_users()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF user_listable</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>

    select * from user_listable;

</programlisting>
      </para>
    </section>

<!-- Function user__get_preferences(in_user_id integer) -->
    <section id="public.function.user-get-preferences-in-user-id-integer"
             xreflabel="()">
      <title id="public.function.user-get-preferences-in-user-id-integer-title">
       user__get_preferences(in_user_id integer)
      </title>
      <titleabbrev id="public.function.user-get-preferences-in-user-id-integer-titleabbrev">
       user__get_preferences(in_user_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>user_preference</seg>
        </seglistitem>
       </segmentedlist>
 
        Returns the preferences row for the user.
        <programlisting>

declare
    v_row user_preference;
BEGIN
    select * into v_row from user_preference where id = in_user_id;

    IF NOT FOUND THEN

        RAISE EXCEPTION &#39;Could not find user preferences for id %&#39;, in_user_id;
    ELSE
        return v_row;
    END IF;
END;
</programlisting>
      </para>
    </section>

<!-- Function user__save_preferences(in_dateformat text, in_numberformat text, in_language text, in_stylesheet text, in_printer text) -->
    <section id="public.function.user-save-preferences-in-dateformat-text-in-numberformat-text-in-language-text-in-stylesheet-text-in-printer-text"
             xreflabel="()">
      <title id="public.function.user-save-preferences-in-dateformat-text-in-numberformat-text-in-language-text-in-stylesheet-text-in-printer-text-title">
       user__save_preferences(in_dateformat text, in_numberformat text, in_language text, in_stylesheet text, in_printer text)
      </title>
      <titleabbrev id="public.function.user-save-preferences-in-dateformat-text-in-numberformat-text-in-language-text-in-stylesheet-text-in-printer-text-titleabbrev">
       user__save_preferences(in_dateformat text, in_numberformat text, in_language text, in_stylesheet text, in_printer text)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>boolean</seg>
        </seglistitem>
       </segmentedlist>
 
        Saves user preferences.  Returns true if successful, false if no preferences
were found to update.
        <programlisting>
BEGIN
    UPDATE user_preference
    SET dateformat = in_dateformat,
        numberformat = in_numberformat,
        language = in_language,
        stylesheet = in_stylesheet,
        printer = in_printer
    WHERE id = (select id from users where username = SESSION_USER);
    RETURN FOUND;
END;
</programlisting>
      </para>
    </section>

<!-- Function voucher__delete(in_voucher_id integer) -->
    <section id="public.function.voucher-delete-in-voucher-id-integer"
             xreflabel="()">
      <title id="public.function.voucher-delete-in-voucher-id-integer-title">
       voucher__delete(in_voucher_id integer)
      </title>
      <titleabbrev id="public.function.voucher-delete-in-voucher-id-integer-titleabbrev">
       voucher__delete(in_voucher_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>integer</seg>
        </seglistitem>
       </segmentedlist>
 
        Deletes the specified voucher from the batch.
        <programlisting>
DECLARE
        voucher_row RECORD;
BEGIN
        SELECT * INTO voucher_row FROM voucher WHERE id = in_voucher_id;
        IF voucher_row.batch_class IN (1, 2, 5) THEN
        DELETE FROM ac_tax_form WHERE entry_id IN (
               SELECT entry_id
                 FROM acc_trans
               WHERE trans_id = voucher_row.trans_id);

                DELETE FROM acc_trans WHERE trans_id = voucher_row.trans_id;
                DELETE FROM ar WHERE id = voucher_row.trans_id;
                DELETE FROM ap WHERE id = voucher_row.trans_id;
                DELETE FROM gl WHERE id = voucher_row.trans_id;
                DELETE FROM voucher WHERE id = voucher_row.id;
                -- DELETE FROM transactions WHERE id = voucher_row.trans_id;
        ELSE
                update ar set paid = amount +
                        (select sum(amount) from acc_trans
                        join chart ON (acc_trans.chart_id = chart.id)
                        where link = &#39;AR&#39; AND trans_id = ar.id
                                AND (voucher_id IS NULL
                                OR voucher_id &lt;&gt; voucher_row.id))
                where id in (select trans_id from acc_trans
                                where voucher_id = voucher_row.id);

                update ap set paid = amount - (select sum(amount) from acc_trans
                        join chart ON (acc_trans.chart_id = chart.id)
                        where link = &#39;AP&#39; AND trans_id = ap.id
                                AND (voucher_id IS NULL
                                OR voucher_id &lt;&gt; voucher_row.id))
                where id in (select trans_id from acc_trans
                                where voucher_id = voucher_row.id);
                DELETE FROM ac_tax_form WHERE entry_id IN
                       (select entry_id from acc_trans
                         where voucher_id = voucher_row.id);

                DELETE FROM acc_trans where voucher_id = voucher_row.id;
        END IF;
        RETURN 1;
END;
</programlisting>
      </para>
    </section>

<!-- Function voucher__list(in_batch_id integer) -->
    <section id="public.function.voucher-list-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.voucher-list-in-batch-id-integer-title">
       voucher__list(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.voucher-list-in-batch-id-integer-titleabbrev">
       voucher__list(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF voucher_list</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves a list of vouchers and amounts attached to the batch.
        <programlisting>
                SELECT v.id, a.invoice, a.invnumber, e.name,
                        v.batch_id, v.trans_id,
                        a.amount, a.transdate, &#39;Payable&#39;, v.batch_class
                FROM voucher v
                JOIN ap a ON (v.trans_id = a.id)
                JOIN entity_credit_account eca
                        ON (eca.id = a.entity_credit_account)
                JOIN entity e ON (eca.entity_id = e.id)
                WHERE v.batch_id = in_batch_id
                        AND v.batch_class = (select id from batch_class
                                        WHERE class = &#39;ap&#39;)
                UNION
                SELECT v.id, a.invoice, a.invnumber, e.name,
                        v.batch_id, v.trans_id,
                        a.amount, a.transdate, &#39;Receivable&#39;, v.batch_class
                FROM voucher v
                JOIN ar a ON (v.trans_id = a.id)
                JOIN entity_credit_account eca
                        ON (eca.id = a.entity_credit_account)
                JOIN entity e ON (eca.entity_id = e.id)
                WHERE v.batch_id = in_batch_id
                        AND v.batch_class = (select id from batch_class
                                        WHERE class = &#39;ar&#39;)
                UNION ALL
                -- TODO:  Add the class labels to the class table.
                SELECT v.id, false, a.source,
                        cr.meta_number || &#39;--&#39;  || co.legal_name ,
                        v.batch_id, v.trans_id,
                        sum(CASE WHEN bc.class LIKE &#39;payment%&#39; THEN a.amount * -1
                             ELSE a.amount  END), a.transdate,
                        CASE WHEN bc.class = &#39;payment&#39; THEN &#39;Payment&#39;
                             WHEN bc.class = &#39;payment_reversal&#39;
                             THEN &#39;Payment Reversal&#39;
                        END, v.batch_class
                FROM voucher v
                JOIN acc_trans a ON (v.id = a.voucher_id)
                JOIN batch_class bc ON (bc.id = v.batch_class)
                JOIN chart c ON (a.chart_id = c.id)
                JOIN ap ON (ap.id = a.trans_id)
                JOIN entity_credit_account cr
                        ON (ap.entity_credit_account = cr.id)
                JOIN company co ON (cr.entity_id = co.entity_id)
                WHERE v.batch_id = in_batch_id
                        AND a.voucher_id = v.id
                        AND (bc.class like &#39;payment%&#39; AND c.link = &#39;AP&#39;)
                GROUP BY v.id, a.source, cr.meta_number, co.legal_name ,
                        v.batch_id, v.trans_id, a.transdate, bc.class

                UNION ALL
                SELECT v.id, false, a.source, a.memo,
                        v.batch_id, v.trans_id,
                        CASE WHEN bc.class LIKE &#39;receipt%&#39; THEN sum(a.amount) * -1
                             ELSE sum(a.amount)  END, a.transdate,
                        CASE WHEN bc.class = &#39;receipt&#39; THEN &#39;Receipt&#39;
                             WHEN bc.class = &#39;receipt_reversal&#39;
                             THEN &#39;Receipt Reversal&#39;
                        END, v.batch_class
                FROM voucher v
                JOIN acc_trans a ON (v.id = a.voucher_id)
                JOIN batch_class bc ON (bc.id = v.batch_class)
                JOIN chart c ON (a.chart_id = c.id)
                JOIN ar ON (ar.id = a.trans_id)
                JOIN entity_credit_account cr
                        ON (ar.entity_credit_account = cr.id)
                JOIN company co ON (cr.entity_id = co.entity_id)
                WHERE v.batch_id = in_batch_id
                        AND a.voucher_id = v.id
                        AND (bc.class like &#39;receipt%&#39; AND c.link = &#39;AR&#39;)
                GROUP BY v.id, a.source, cr.meta_number, co.legal_name ,
                        a.memo, v.batch_id, v.trans_id, a.transdate, bc.class
                UNION ALL
                SELECT v.id, false, g.reference, g.description,
                        v.batch_id, v.trans_id,
                        sum(a.amount), g.transdate, &#39;GL&#39;, v.batch_class
                FROM voucher v
                JOIN gl g ON (g.id = v.trans_id)
                JOIN acc_trans a ON (v.trans_id = a.trans_id)
                WHERE a.amount &gt; 0
                        AND v.batch_id = in_batch_id
                        AND v.batch_class IN (select id from batch_class
                                        where class = &#39;gl&#39;)
                GROUP BY v.id, g.reference, g.description, v.batch_id,
                        v.trans_id, g.transdate
                ORDER BY 7, 1
</programlisting>
      </para>
    </section>

<!-- Function voucher_get_batch(in_batch_id integer) -->
    <section id="public.function.voucher-get-batch-in-batch-id-integer"
             xreflabel="()">
      <title id="public.function.voucher-get-batch-in-batch-id-integer-title">
       voucher_get_batch(in_batch_id integer)
      </title>
      <titleabbrev id="public.function.voucher-get-batch-in-batch-id-integer-titleabbrev">
       voucher_get_batch(in_batch_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>batch</seg>
        </seglistitem>
       </segmentedlist>
 
        Retrieves basic batch information based on batch_id.
        <programlisting>
DECLARE
        batch_out batch%ROWTYPE;
BEGIN
        SELECT * INTO batch_out FROM batch b WHERE b.id = in_batch_id;
        RETURN batch_out;
END;
</programlisting>
      </para>
    </section>

<!-- Function wage__list_for_entity(in_entity_id integer) -->
    <section id="public.function.wage-list-for-entity-in-entity-id-integer"
             xreflabel="()">
      <title id="public.function.wage-list-for-entity-in-entity-id-integer-title">
       wage__list_for_entity(in_entity_id integer)
      </title>
      <titleabbrev id="public.function.wage-list-for-entity-in-entity-id-integer-titleabbrev">
       wage__list_for_entity(in_entity_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_wage</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_wage WHERE entity_id = $1;
</programlisting>
      </para>
    </section>

<!-- Function wage__list_types(in_country_id integer) -->
    <section id="public.function.wage-list-types-in-country-id-integer"
             xreflabel="()">
      <title id="public.function.wage-list-types-in-country-id-integer-title">
       wage__list_types(in_country_id integer)
      </title>
      <titleabbrev id="public.function.wage-list-types-in-country-id-integer-titleabbrev">
       wage__list_types(in_country_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF payroll_income_type</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM payroll_income_type where country_id = $1
</programlisting>
      </para>
    </section>

<!-- Function wage__save(in_rate numeric, in_entity_id integer, in_type_id integer) -->
    <section id="public.function.wage-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer"
             xreflabel="()">
      <title id="public.function.wage-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer-title">
       wage__save(in_rate numeric, in_entity_id integer, in_type_id integer)
      </title>
      <titleabbrev id="public.function.wage-save-in-rate-numeric-in-entity-id-integer-in-type-id-integer-titleabbrev">
       wage__save(in_rate numeric, in_entity_id integer, in_type_id integer)
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>PLPGSQL</seg>
         <seg>payroll_wage</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
DECLARE
  return_wage payroll_wage;
BEGIN

UPDATE payroll_wage
   SET rate = in_rate
 WHERE entity_id = in_entity_id and in_type_id;


IF NOT FOUND THEN
    INSERT INTO payroll_wage (entity_id, type_id, rate)
    VALUES (in_entity_id, in_type_id, in_rate);
END IF;

SELECT * INTO return_wage FROM payroll_wage
             WHERE entity_id = in_entity_id and in_type_id;

RETURN return_wage;
END;
</programlisting>
      </para>
    </section>

<!-- Function warehouse__list() -->
    <section id="public.function.warehouse-list"
             xreflabel="()">
      <title id="public.function.warehouse-list-title">
       warehouse__list()
      </title>
      <titleabbrev id="public.function.warehouse-list-titleabbrev">
       warehouse__list()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF warehouse</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM warehouse ORDER BY DESCRIPTION;
</programlisting>
      </para>
    </section>

<!-- Function warehouse__list_all() -->
    <section id="public.function.warehouse-list-all"
             xreflabel="()">
      <title id="public.function.warehouse-list-all-title">
       warehouse__list_all()
      </title>
      <titleabbrev id="public.function.warehouse-list-all-titleabbrev">
       warehouse__list_all()
      </titleabbrev>

      <para>
       <segmentedlist>
        <title>Function Properties</title>
        <?dbhtml list-presentation="list"?>
        <segtitle>Language</segtitle>
        <segtitle>Return Type</segtitle>
        <seglistitem>
         <seg>SQL</seg>
         <seg>SET OF warehouse</seg>
        </seglistitem>
       </segmentedlist>
 
       
        <programlisting>
SELECT * FROM warehouse order by description;
</programlisting>
      </para>
    </section>

  </chapter>

</book>

